[英]Overlaying of 2 images doesnt work properly
我正在尝试在JPEG图像上合并两个图像PNG / TIFF文件。 我正在使用以下代码
try {
image = ImageIO.read(new File("C:\\Users\\user\\Desktop\\test\\a.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedImage overlay = null;
try {
overlay = ImageIO.read(new File("C:\\Users\\user\\Desktop\\test\\b.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// create the new image, canvas size is the max. of both image sizes
int w = Math.max(image.getWidth(), overlay.getWidth());
int h = Math.max(image.getHeight(), overlay.getHeight());
BufferedImage combined = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
// paint both images, preserving the alpha channels
Graphics2D g = combined.createGraphics();
/**Set Antialias Rendering**/
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
/**
* Draw background image at location (0,0)
* You can change the (x,y) value as required
*/
g.drawImage(image, 0, 0, null);
/**
* Draw foreground image at location (0,0)
* Change (x,y) value as required.
*/
g.drawImage(overlay, 0, 0, null);
g.dispose();
// Save as new image
try {
ImageIO.write(combined, "JPG", new File("C:\\Users\\user\\Desktop\\test\\c.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
但是,最终形成的图像不符合我的要求。 为了清楚起见,请参考所附图像。
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
class CombineImages {
public static void main(String[] args) throws Exception {
URL urlImage1 = new URL("http://i.stack.imgur.com/T5uTa.png");
// Load the FG image (must have transparent parts)
final Image fgImage = ImageIO.read(urlImage1);
int w = fgImage.getWidth(null);
int h = fgImage.getHeight(null);
// Create a non-trasparent BG image
final BufferedImage bgImage =
new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
// Create the final image
final BufferedImage finalImage =
new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
Graphics2D g = finalImage.createGraphics();
g.drawImage(bgImage, 0, 0, null);
g.drawImage(fgImage, 0, 0, null);
g.dispose();
Runnable r = new Runnable() {
@Override
public void run() {
JPanel gui = new JPanel(new GridLayout(1,0,5,5));
gui.add(new JLabel(new ImageIcon(bgImage)));
gui.add(new JLabel(new ImageIcon(fgImage)));
gui.add(new JLabel(new ImageIcon(finalImage)));
JOptionPane.showMessageDialog(null, gui);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.