我目前有一个使用 Vaadin 的上传组件运行的上传功能,但我不确定如何将文件上传的图像结果绘制到 Canvas 中,因为我是 Vaadin/Java 的新手。图片可以成功上传,但 Canvas 不会出现。我需要一 block Canvas ,因为我将用它在随后上传的图像上绘制方框。
这是我的代码:
package com.vaadin.starter.beveragebuddy.backend;
import com.vaadin.flow.component.dependency.HtmlImport;
import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.upload.Upload;
import com.vaadin.flow.component.upload.receivers.MultiFileMemoryBuffer;
import com.vaadin.flow.router.Route;
import java.awt.Canvas;
public class MainLayout extends VerticalLayout {
private Canvas canvas;
public MainLayout() {
H2 title = new H2("Image Annotation Tool");
MultiFileMemoryBuffer buffer = new MultiFileMemoryBuffer();
Upload upload = new Upload(buffer);
upload.addSucceededListener(event -> {
// Component component = createComponent(event.getMIMEType(),
// event.getFileName(),
// buffer.getInputStream(event.getFileName()));
// showOutput(event.getFileName(), component, output);
});
add(upload);
}
public void Test() {
Frame frame = new Frame("Testing");
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.add(new ImageCanvas());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class ImageCanvas extends Canvas {
private BufferedImage img;
public ImageCanvas() {
try {
img = ImageIO.read(new File("upload"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
@Override
public Dimension getPreferredSize() {
return img == null ? new Dimension(1580, 800) : new Dimension(img.getWidth(), img.getHeight());
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (img != null) {
int x = (getWidth() - img.getWidth()) / 2;
int y = (getHeight() - img.getHeight()) / 2;
g.drawImage(img, x, y, this);
}
}
}
}
非常感谢任何帮助,谢谢!
最佳答案
遗憾的是,AWT(桌面组件)Canvas 无法在 Vaadin(Web)应用程序中使用。 有多种方法可以实现您的想法:
文件上传到服务器,使用
javax.imageio.ImageIO
在服务器端(正如您已经完成的一半一样),然后使用StreamResource
将其作为图像资源下载回客户端和Image
使用 JavaScript 进行客户端 html5 canvas 操作。
您需要首先定义需要实现什么
关于java - 如何使用 Vaadin 将图像上传到 Canvas ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53078846/