简体   繁体   中英

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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM