我正在尝试在我的onPaint方法中显示图像,但不断获得黑色背景。我显示的图像是JPanel.print(Graphics)或JPanel.paint(Graphics)的结果。所以我将此结果转换为png文件,该文件存储在数据库中。稍后,该图像由用户加载和转换。这个过程给了我一个黑色的背景。
以下是代码:
首先创建图像:
public static BufferedImage createBufferedImageFromView(JPanel panel){
int w = panel.getWidth();
int h = panel.getHeight();
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
g.setBackground(new Color(0, 0, 0, 0));
g.clearRect(0, 0, bi.getWidth(), bi.getHeight());
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, 0.0f));
panel.setOpaque(false);
panel.repaint();
panel.print(g);
return bi;
}
然后我在onPaint()方法中绘制它:
public void paint(Graphics g) {
super.paint(g);
ParameterBlock params = new ParameterBlock();
params.addSource(previewImage); //source is the input image
int w = previewImage.getWidth(); //Set to the original width of the image
int h = previewImage.getHeight(); //Set to the original height of image
Point tl = new Point((int)cornersTrans[0].getX(), (int)cornersTrans[0].getY()); //The new top left corner
Point tr = new Point((int)cornersTrans[1].getX(), (int)cornersTrans[1].getY()); //The new top right corner
Point bl = new Point((int)cornersTrans[2].getX(), (int)cornersTrans[2].getY()); //The new bottom left corner
Point br = new Point((int)cornersTrans[3].getX(), (int)cornersTrans[3].getY()); //The new bottom right corner
try {
params.add(new WarpPerspective(PerspectiveTransform.getQuadToQuad(0,0, 0, h, w, h, w, 0, tl.x, tl.y, bl.x, bl.y, br.x, br.y, tr.x, tr.y).createInverse()));
} catch (NoninvertibleTransformException e) {
e.printStackTrace();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
if(!isInMovement)
params.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC));
PlanarImage image = JAI.create("warp", params);
int y0 = (int) (cornersTrans[0].getY() < cornersTrans[1].getY() ? cornersTrans[0].getY() : cornersTrans[1].getY());
int x0 = (int) (cornersTrans[0].getX() < cornersTrans[2].getX() ? cornersTrans[0].getX() : cornersTrans[2].getX());
int x1 = (int) (cornersTrans[3].getX() > cornersTrans[1].getX() ? cornersTrans[3].getX() : cornersTrans[1].getX());
int y1 = (int) (cornersTrans[3].getY() > cornersTrans[2].getY() ? cornersTrans[3].getY() : cornersTrans[2].getY());
Graphics2D g2d = (Graphics2D) g;
// g2d.setBackground(new Color(0,255,0,0)); // g2d.clearRect(0,0,9999,9999); g2d.drawImage((Image)image.getAsBufferedImage(),x0,y0,x1,y1,0,0,image.getWidth(),image.getHeight(),null);
有关如何修复黑色背景的想法吗?
谢谢!