I'm using wand in a Django project, to generate a thumbnail from different kind of files, e.g pdf, all the thumbnail generation process is done in memory, the source file is get from a request and the thumbnail is saved to a temporary file, then Django FileFiled saves the image in the correct path, but the thumbnail generated keeps the initial size, this is my code:
with image.Image(file=self.content.file, format="png") as im: # self.content is a django model FileField didn't saved yet, so the file inside is still in memory (from the request)
im.resize(200, 200)
name = self.content.file.name
self.temp = tempfile.NamedTemporaryFile()
im.save(file=self.temp)
self.thumbnail = InMemoryUploadedFile(self.temp, None, name + ".png", 'image/png', 0, 0, None) # then self.thumnail as FileField saves the image
Do you have any idea what happen? could be a bug? I've already reported it as issue on wand github page.
The problem comes from the fact that your PDF has more than one page. If you only resize the first page (which is the one you want to display), it works. Try adding the following line after your with statement:
im = image.Image(image=im.sequence[0])
But I agree with you that your version should work as well.
Related
I am manipulating an image using Pillow, and then want to send it to Discord. My code: https://paste.pythondiscord.com/comebefupo.py
When using image.show(), the manipulated image is shown fine.
however, when I want to upload the image to Discord, the bot gets stuck and no error is thrown:
got bytes from direct image string
got bytes from member/user pfp or str
opened image
opened draw
drew top text
drew bottom text
prepared buffer
prepared file
# Bot just gets stuck here, no errors
According to multiple sources (1, 2), I am doing the right thing by saving the image into a BytesIO stream, and then using seek(0).
According to the documentation for a discord.File, it takes a io.BufferedIOBase which is (I believe) I put in.
EDIT:
saving the image first, and then sending that works.
# Return whole image object
return image
self.convert_bytes(image_bytes, top_text, bottom_text).save('image.png')
await ctx.send(file=discord.File('image.png'))
I have no clue why this works, and the other thing doesnt...
I had a similar problem last week, this was the code I used to send the image
with BytesIO() as image_binary:
image.save(image_binary, 'PNG')
image_binary.seek(0)
await ctx.send(file=discord.File(fp=image_binary, filename='image.png'))
This is not a full answer but it might help.
image_file = discord.File(io.BytesIO(image_bytes.encode()),filename=f"{name}.png")
await ctx.send(file=image_file )
I'm a noob PyQt5 user following a tutorial and I'm confused how I might extend the sample code below.
The two handlers canInsertFromMimeData and insertFromMimeData Qt5 methods accept an image mime datatype dragged and dropped onto document (that works great). They both receive a signal parameter source which receives a QMimeData object.
However, If I try to paste an image copied from the Windows clipboard into the document it just crashes as there is no handler for this.
Searching the Qt5 documentation at https://doc.qt.io/qt-5/qmimedata.html just leads me to further confusion as I'm not a C++ programmer and I'm using Python 3.x and PyQt5 to do this.
How would I write a handler to allow an image copied to the clipboard to be pasted into the document directly?
class TextEdit(QTextEdit):
def canInsertFromMimeData(self, source):
if source.hasImage():
return True
else:
return super(TextEdit, self).canInsertFromMimeData(source)
def insertFromMimeData(self, source):
cursor = self.textCursor()
document = self.document()
if source.hasUrls():
for u in source.urls():
file_ext = splitext(str(u.toLocalFile()))
if u.isLocalFile() and file_ext in IMAGE_EXTENSIONS:
image = QImage(u.toLocalFile())
document.addResource(QTextDocument.ImageResource, u, image)
cursor.insertImage(u.toLocalFile())
else:
# If we hit a non-image or non-local URL break the loop and fall out
# to the super call & let Qt handle it
break
else:
# If all were valid images, finish here.
return
elif source.hasImage():
image = source.imageData()
uuid = hexuuid()
document.addResource(QTextDocument.ImageResource, uuid, image)
cursor.insertImage(uuid)
return
super(TextEdit, self).insertFromMimeData(source)
code source: https://www.learnpyqt.com/examples/megasolid-idiom-rich-text-editor/
I was exactly in the same position as you. I am also new to Python, so there might be mistakes.
The variable uuid in document.addResource(QTextDocument.ImageResource, uuid, image) is not working. It should be a path -> QUrl(uuid).
Now you can insert the image. However, because the path to an image from the clipboard is changing, it would be better to use a different path, for example to the directory where you are also saving the files.
Also be aware that the user has to select the file type when saving (.html)
For my own project I am going to print the file as pdf. That way you dont have to worry about paths to images ^-^
I got around this by converting to base64 inline embedding of the images, then no resource files as it is all in one file.
I opening an image file using the pillow(PIL) library and saving it again under a different name. But when I save the image under the different name it takes my original 300 DPI file and makes it a 72 DPI file. I tried adding dpi=(300, 300) But still no success.
See code
from PIL import Image
image = Image.open('image-1.jpg')
image.save('image-2.jpg' , dpi=(300, 300))
My original file(image-1.jpg)
https://www.dropbox.com/s/x7xj6hyoemv3t94/image_info_1.jpg?raw=1
My copied file(image-2.jpg)
https://www.dropbox.com/s/dpcnkfozefobopn/image_info_2.jpg?raw=1
Notice how they still have the same image size: 8.45.
Thanks to #HansHirse explaining that the meta data was missing AKA exif information I saved the image with the exif info and it worked
from PIL import Image
image = Image.open('image-1.jpg')
exif = image.info['exif']
image.save('image-2.jpg' , exif=exif)
So, I wrote a small program to clone masks for 30k+ images. Every image and masks sample there are converted to jpeg format. However, when I'm trying to start a program it creates some masks and then stops, throwing an error written in the title. It is quiet strange that OpenCV can't create jpeg image, since it is a default format for it.
Question is: how to make OpenCV actually save those newly created masks?
Here is the code:
folders = ["162", "204", "260", "1093", "3297", "5020", "10066", "10870", "10917", "11160", "11331", "17218", "19106", "19306", "19388"]
for folder in folders:
print(folder)
names = os.listdir(folder)
os.chdir("%s/masks"%folder)
image = cv2.imread("%s.jpeg"%folder)
for name in names:
print(name)
cv2.imwrite(img=image, filename=name)
I am converting different images and pdf files with "gm" module for nodejs. Image types go successfully but when I want to convert PDF to image have problems. I need to covert only one selected page from pdf file to jpg/png. If I pass whole pdf file to "gm" it saves to image only first page, but I cannot find the way to save another page.
gm(file).toBuffer(format.toUpperCase(),
function (err, buffer) {
// so in buffer now we have converted image
}
Thank you.
You can use gm.selectFrame like this
gm(file).selectFrame(0).toBuffer() // To get first page
gm(file).selectFrame(1).toBuffer() // To get second page
// for only first pdf page use:
gm(file, 'pdf.pdf[0]').toBuffer(...)
// for only second pdf page use:
gm(file, 'pdf.pdf[1]').toBuffer(...)
There is spindrift for manipulating pdf (includes image conversion).
You can define your pdf using (You don't have you use all of the commands):
var pdf = spindrift('in.pdf')
.pages(7, 24)
.page(1)
.even()
.odd()
.rotate(90)
.compress()
.uncompress()
.crop(100, 100, 300, 200) // left, bottom, right, top
Later on convert to image:
// Use the 'index' property of an image element to extract an image:
pdf.extractImageStream(0)
If you have to use gm, you can do what #Ben Fortune suggested in his comment and split the pdf first.