image.save() not saving file with specified name - python

using following code to save all tiffs to a single PDF
from PIL import Image
imagelist[0].save(fp=path_to_saving_location+"specified_name.pdf",save_all =True, append_images = imagelist[1:])
instead it is saving the PDF as 001.pdf.
Am I doing anything wrong here?

Create a variable called fullpath in the line above the save statement and set its value how you think.
Print it so you can check it. Then use:
imagelist[0].save(fullpath, save_all =True, append_images = imagelist[1:])
Also, consider deleting 001.pdf before you run your program, so you can be sure if your program really does create it.

Related

Cannot save multiple files with PIL save method

I have modified a vk4 converter to allow for the conversion of several .vk4 files into .jpg image files. When ran, IDLE does not give me an error, but it only manages to convert one file before ending the process. I believe the issue is that image.save() only seems to affect a single file and I have been unsuccessful in looping that command to extend to all other files in the directory.
Code:
import numpy as np
from PIL import Image
import vk4extract
import os
os.chdir(r'path\to\directory')
root = ('.\\')
vkimages = os.listdir(root)
for img in vkimages:
if (img.endswith('.vk4')):
with open(img, 'rb') as in_file:
offsets = vk4extract.extract_offsets(in_file)
rgb_dict = vk4extract.extract_color_data(offsets, 'peak', in_file)
rgb_data = rgb_dict['data']
height = rgb_dict['height']
width = rgb_dict['width']
rgb_matrix = np.reshape(rgb_data, (height, width, 3))
image = Image.fromarray(rgb_matrix, 'RGB')
image.save('sample.jpeg', 'JPEG')
How do I prevent the converted files from being overwritten while using the PIL module?
Thank you.
It is saving every file, but since you are always providing the same name to each file (image.save('sample.jpeg', 'JPEG')), only the last one will be saved and all the other ones will be overwritten. You need to specify different names to every file. There are several ways of doing it. One is adding the index when looping using enumerate():
for i, img in enumerate(vkimages):
and then using the i on the name of the file when saving:
image.save(f'sample_{i}.jpeg', 'JPEG')
Another way is to use the original filename and replace the extension. From your code, it looks like the files are .vk4 files. So another possibility is to save with the same name but replacing .vk4 to .jpeg:
image.save(img.replace('.vk4', '.jpeg'), 'JPEG')

Save images using Pillow without overwriting already saved images

I want to save around 12000 images generated from a particular code. I will be able to save these images only using my Project VPN which keeps disconnecting some times and then the entire process of saving takes place by overwriting already saved images and taking again a lot of time.
How do I avoid this?
from PIL import Image
dirc = os.path.join(r"C:\\", "DATASET", "Images", f"{measurename}")
if not os.path.exists(dirc):
os.makedirs(dirc)
gray_image_cropped.save(os.path.join(dirc, f"{id}_seg{obj}.tif"))
Check whether the file exists:
from PIL import Image
dirc = os.path.join(r"C:\\", "DATASET", "Images", f"{measurename}")
if not os.path.exists(dirc):
os.makedirs(dirc)
outfile = os.path.join(dirc, f"{id}_seg{obj}.tif"
if not os.path.exists(outfile):
gray_image_cropped.save(outfile))

Python: SpooledTemporaryFile suffix not working

I want to write an image using opencv to a temporary file, get the path of that temporary file and pass that path to a function.
import cv2 as cv
from tempfile import NamedTemporaryFile, SpooledTemporaryFile
img = create_my_awesome_image()
with NamedTemporaryFile(suffix=".png") as temp:
print(temp.name)
cv.imwrite(temp.name, img) # this one sparks joy
with SpooledTemporaryFile(max_size=1000000, suffix=".png") as temp:
print(temp.name)
cv.imwrite(temp.name, img) # this one does not
The first print prints C:\Users\FLORIA~1\AppData\Local\Temp\tmpl2i6nc47.png.
While the second print prints: None.
Using NamedTemporaryFile works perfectly find. However, because the second print prints None, I cannot use the SpooledTemporaryFile together with opencv. Any ideas why the prefix argument of SpooledTemporaryFile is ignored?
The problem is that a spooled file (such as a SpooledTemporaryFile) doesn't exist on the disk, so it also doesn't have a name.
However, note that cv2.imread() will take a file name as an argument, meaning that it will handle the file opening and it doesn't support spooled files.
If you are only working with png images, they are not encoded, meaning that the variable img already contains the image data in memory and there is nothing else for you to do, just call cv2.imwrite() when you want to save it to the disk. If you want to use a temporary file, it has to be a NamedTemporaryFile.
If you want to handle an encoded image format in memory, such as jpg, you can use cv2.imencode() for that purpose, as in this answer.

PIL - Open image is not able to be read

Im trying to read a file's format so I can correctly assign a new name to it and write it to disk, but when the Image.open() is on the image, I cannot write the image to disk. So for example :
This works:
>>>file = open('708864.jpg')
>>> open('lala.jpeg', 'w').write(file.read())
But, this doesn't
>>>import Image
>>>im = Image.open('708864.jpg')
>>> im.format
>>> open('lala.jpeg', 'w').write(file.read())
It creates a corrupted file (lala.jpeg) which is unable to be opened by any software.
I'm suspecting the culprit is the Image.open(). And after trying to locate an Image.close() statement, I was unable to find one. How would you "close" this image, so I can still write it to disk?
As suggested in my comment, im.save('lala.jpg') is the way to go.
For all the other fun methods on an Image object, you can look at the documentation.
Some workaround, it is just idea:
import Image
import StringIO
file = open('/home/mrok/1.jpg')
output = StringIO.StringIO(file.read())
im = Image.open('/home/mrok/1.jpg')
im.format
open('/home/mrok/2.jpg', 'w').write(output.getvalue())
output.close()
As said in a comment, I ended up using a function I never knew about before, Image.save() , which quickly solves my problem.

Programmatically save image to Django ImageField 2

I've read many answers and tried all of this in the shell, but does not want to save my local image correctly, he truncate files. When image size is 400kb, he create file in media dir with size 10-30kb. I don't know why. For example i have image with path d:/1.png. I tried
from django.core.files import File
fileObject=File(open("d:/1.png"))
object.image.save('1.png',fileObject,True)
fileObject.size show correct size of image, but object.image.size is not correct and file, what he save not full.
Also i tried
from django.core.files.temp import NamedTemporaryFile
temp = NamedTemporaryFile()#with delete=True TypeError: __init__() got an unexpected keywork argument 'delete'
temp.write(open('d:/1.png').read())
temp.flush()
f=File(temp)#f.size not correct
object.image.save('1.png',f,True)
and object.image.size and file not correct, file not full.
I tried using StringIO, but this not work too. I don't know what try to save this images correctly.
Please, help.
you have to change mode to binary
fileObject=File(open("d:/1.png", mode="rb"))

Categories

Resources