我有Java
Spring MVC
个应用程序,其中有一个选项可以上传图像并保存到服务器。我有以下方法:
@RequestMapping(value = "/uploaddocimagecontentsubmit", method = RequestMethod.POST)
public String createUpdateFileImageContentSubmit(@RequestParam("file") MultipartFile file, ModelMap model)
{
//methods to handle file upload
}
我现在正在尝试减小图像的大小,参考以下内容:
increasing-resolution-and-reducing-size-of-an-image-in-java和decrease-image-resolution-in-java
我面临的问题是,在上面的例子中,我们正在处理保存到指定位置的java.io.File
个对象。我不想保存图像。有什么方法可以使用类似的东西来压缩我的Multipart Image文件并继续上传。
答案 0 :(得分:0)
这是我第一次深入研究 ImageIO 包。我遇到了 MemoryCacheImageOutputStream,它允许您将图像输出流写入输出流,即 ByteArrayOutputStream。从那里,可以在压缩后使用 toByteArray() 和 toString() 检索数据。我使用 toByteArray,因为我将图像存储到 postgresql 并将图像存储为字节数组。我知道这已经晚了,但我希望它可以帮助某人。
private byte[] compressImage(MultipartFile mpFile) {
float quality = 0.3f;
String imageName = mpFile.getOriginalFilename();
String imageExtension = imageName.substring(imageName.lastIndexOf(".") + 1);
// Returns an Iterator containing all currently registered ImageWriters that claim to be able to encode the named format.
// You don't have to register one yourself; some are provided.
ImageWriter imageWriter = ImageIO.getImageWritersByFormatName(imageExtension).next();
ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // Check the api value that suites your needs.
// A compression quality setting of 0.0 is most generically interpreted as "high compression is important,"
// while a setting of 1.0 is most generically interpreted as "high image quality is important."
imageWriteParam.setCompressionQuality(quality);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// MemoryCacheImageOutputStream: An implementation of ImageOutputStream that writes its output to a regular
// OutputStream, i.e. the ByteArrayOutputStream.
ImageOutputStream imageOutputStream = new MemoryCacheImageOutputStream(baos);
// Sets the destination to the given ImageOutputStream or other Object.
imageWriter.setOutput(imageOutputStream);
BufferedImage originalImage = null;
try (InputStream inputStream = mpFile.getInputStream()) {
originalImage = ImageIO.read(inputStream);
} catch (IOException e) {
String info = String.format("compressImage - bufferedImage (file %s)- IOException - message: %s ", imageName, e.getMessage());
logger.error(info);
return baos.toByteArray();
}
IIOImage image = new IIOImage(originalImage, null, null);
try {
imageWriter.write(null, image, imageWriteParam);
} catch (IOException e) {
String info = String.format("compressImage - imageWriter (file %s)- IOException - message: %s ", imageName, e.getMessage());
logger.error(info);
} finally {
imageWriter.dispose();
}
return baos.toByteArray();
}
答案 1 :(得分:-1)
为什么不在上传前在客户端调整大小?这将节省一些带宽
BlueImp JQuery Upload可以做到这一点