【发布时间】:2017-06-11 23:13:43
【问题描述】:
我有一个基于 Spring Web 模型-视图-控制器 (MVC) 框架的项目。 Spring Web 模型-视图-控制器 (MVC) 框架的版本是 3.2.8。 我正在阅读图片
public static void main(String[] args) {
BufferedImage img = null;
try {
img = ImageIO.read(new File("C:/tmp/device.jpg"));
} catch (IOException e) {
}
System.out.println ("img -> " + img);
}
这个结果很好用:
img -> BufferedImage@18e8541: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@1ce85c4 transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 480 height = 640 #numDataElements 3 dataOff[0] = 2
但是当我在我的 Spring-MVC 应用中上传 same 图像时:
MultipartFile file = productForm.getAttachment();
System.out.println ("productForm.getAttachment() ------------------> " + productForm.getAttachment());
System.out.println ("productForm.getAttachment().getContentType() -> " + productForm.getAttachment().getContentType());
System.out.println ("productForm.getAttachment().getSize() --------> " + productForm.getAttachment().getSize());
byte[] result = new byte[(int) file.getSize()];
Image img = new Image();
img.setContent(result);
ByteArrayInputStream in = new ByteArrayInputStream(img.getContent());
BufferedImage img2 = null;
try {
img2 = ImageIO.read(in);
System.out.println ("IMAGE CONTENT2 ------> " + img2);
} catch (IOException e) {
}
productForm.getAttachment() ------------------> org.springframework.web.multipart.commons.CommonsMultipartFile@1f1bc67
productForm.getAttachment().getContentType() -> image/jpeg
productForm.getAttachment().getSize() --------> 28704
,我遇到过 img2 为空!!!
这里是图片类
public class Image implements java.io.Serializable {
private Long id;
private byte[] content;
public Image() {
}
public Image(Image image) {
this.id = image.getId();
this.content = image.getContent();
}
public Image(byte[] content) {
this.content = content;
}
@Id
@Column(name = "ID", unique = true, nullable = false, precision = 38, scale = 0)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "CONTENT", nullable = false)
@Lob
@Basic(fetch = FetchType.LAZY)
public byte[] getContent() {
return this.content;
}
public void setContent(byte[] content) {
this.content = content;
}
}
【问题讨论】:
-
你检查过那个文件,结果和img不为空,以确保问题不在那里。
-
也许你有一个...
IOException? :D -
不,我看到了图像内容 2 ------>
-
@AmadeuCabanilles 您可能应该将该行添加到您的输出中,以避免混淆。无论如何,
Image是什么类?setContent(..)/getContent()方法有什么作用?在我看来,您传递的是一个空数组,却忘记从file复制实际数据。如果不是,很可能是上传过程中的某些东西损坏了图像数据。尝试将in的内容直接写入磁盘,然后在十六进制编辑器中查看它的样子。 -
@AmadeuCabanilles 正如我所想,问题在于您永远不会将任何字节复制到
result。您只需将result初始化为长度为file.getSize()的空数组。然后将此空数组传递给您的Image实例并返回给ByteArrayInputStream。您可能打算将result初始化为file.getBytes()。
标签: java spring spring-mvc image-processing javax.imageio