我有以下代码上传图片并在网页上显示
// 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);
问题是,它显示了完整的分辨率,我想缩放(因此它保持成比例),它下降到180px宽度。图片也需要保存为原始的filename_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)
答案 0 :(得分:1)
您无法直接使用第三方工具(如Scalr)直接使用Vaadin对象,而无需将其调整到另一个。 "嵌入式"是一个Vaadin类,而SclaR期望一个" BufferedImage"。
因此,您首先需要从Embedded对象中提取File对象:
File imageFile = ((FileResource)(image.getSource()).getSourceFile();
然后,使用ImageIO将其加载到BufferedImage中,如您指向的链接(What is the best way to scale images in Java?)中所述
BufferedImage img = ImageIO.read(...); // load image
然后,你有了你正在寻找的BufferedImage对象。