【发布时间】:2015-10-05 22:11:02
【问题描述】:
我有以下代码可以上传图片并在网页上显示
// Show uploaded file in this placeholder
final Embedded image = new Embedded("Uploaded Image");
image.setVisible(false);
// Implement both receiver that saves upload in a file and
// listener for successful upload
class ImageUploader implements Receiver, SucceededListener {
public File file;
public OutputStream receiveUpload(String filename, String mimeType) {
// Create upload stream
FileOutputStream fos = null; // Stream to write to
try {
// Open the file for writing.
file = new File(tmp_dir + "/" + filename);
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
return null;
}
return fos; // Return the output stream to write to
}
public void uploadSucceeded(SucceededEvent event) {
// Show the uploaded file in the image viewer
image.setVisible(true);
image.setSource(new FileResource(file));
}
};
ImageUploader receiver = new ImageUploader();
// Create the upload with a caption and set receiver later
Upload upload = new Upload("Upload Image Here", receiver);
upload.setButtonCaption("Start Upload");
upload.addSucceededListener(receiver);
final FormLayout fl = new FormLayout();
fl.setSizeUndefined();
fl.addComponents(upload, image);
问题是,它显示了全分辨率,我想将其缩放(因此保持成比例)到 180 像素宽度。图片还需要保存为原始文件名_resized.jpg,但我似乎无法按比例缩放。网络上的一些指南讨论了调整大小(但随后图片被扭曲)或者它给 Vaadin 带来了一些问题。
更新: 添加了 Scarl jar(来自 this answer)),因为使用以下代码会很容易:
BufferedImage scaledImage = Scalr.resize(image, 200);
但这会产生以下错误:
The method resize(BufferedImage, int, BufferedImageOp...) in the type Scalr is not applicable for the arguments (Embedded, int)
我无法投射,因为 Cannot cast from Embedded to BufferedImage 错误
更新:使用以下代码,我可以转换为正确的类型
File imageFile = (((FileResource) (image.getSource())).getSourceFile());
BufferedImage originalImage = ImageIO.read(imageFile) ;
BufferedImage scaledImage = Scalr.resize(originalImage, 200);
但现在我无法显示图像..
final FormLayout fl = new FormLayout();
fl.setSizeUndefined();
fl.addComponents(upload, scaledImage);
因为错误The method addComponents(Component...) in the type AbstractComponentContainer is not applicable for the arguments (Upload, BufferedImage)
【问题讨论】: