在我的模型中,我想通过覆盖保存方法来格式化图像字段
我已经在模型中完成了
public void downloadcsv() {
String server = "servername.host";
int port = 21;
String user = "username";
String pass = "password";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
String remoteFile = "/serverpath/daten.csv";
File downloadFile = new File("localpath/daten.csv");
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));
boolean success = ftpClient.retrieveFile(remoteFile, outputStream);
outputStream.close();
if (success) {
System.out.println("File has been downloaded successfully.");
}
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
但是出现此属性错误
from PIL import Image as Img
from io import StringIO
from django.core.files.uploadedfile import InMemoryUploadedFile
class Blog(models.Model):
Blog_image= models.ImageField(upload_to="...", blank=True)
def save(self, *args, **kwargs):
if self.Blog_image:
image = Img.open(StringIO.StringIO(self.Blog_image.read()))
image.thumbnail((900,300), Img.ANTIALIAS)
output = StringIO.StringIO()
image.save(output, format='JPEG', quality=150)
output.seek(0)
self.Blog_image = InMemoryUploadedFile(output,'ImageField', "%s.jpg" %self.Blog_image.name, 'image/jpeg', output.len, None)
super(Blog, self).save(*args, **kwargs)
任何人都可以向我解释为什么我会收到此错误吗?
我的python版本是3.6.4
我的Django版本是2.0.7
答案 0 :(得分:1)
得到解决方案
from PIL import Image
from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
import sys
def save(self, *args, **kwargs):
imageTemproary = Image.open(self.Blog_image)
outputIoStream = BytesIO()
imageTemproaryResized = imageTemproary.resize( (900,300) )
imageTemproaryResized.save(outputIoStream , format='JPEG', quality=150)
outputIoStream.seek(0)
self.Blog_image = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" %self.Blog_image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None)
super(Blog, self).save(*args, **kwargs)
使用BytesIO进行操作,效果很好
答案 1 :(得分:1)
输出= StringIO.StringIO()
将其更改为:
输出= StringIO()
您已经导入了io.StringIO()。