图片叠加
try {
/* 1 读取第一张图片*/
File fileOne = new File("1.png");
BufferedImage imageFirst = ImageIO.read(fileOne);
/* 2读取第二张图片 */
File fileTwo = new File("2.png");
BufferedImage imageSecond = ImageIO.read(fileTwo);
//创建一个最底层画布 高和宽为第一章图片的高和宽
BufferedImage image = new BufferedImage(imageFirst.getWidth(),imageFirst.getHeight(),BufferedImage.TYPE_INT_ARGB);
//通过底图创建画笔
Graphics graphics = image.getGraphics();
//在底图上画第一张图
graphics.drawImage(imageFirst,0,0,null);
//在底图上画第二张图 参数: 图片, x轴坐标, y轴坐标, null
graphics.drawImage(imageSecond,0,0,null);
//在图片上写文字
graphics.drawString("i am a str", 10, 30);
//输出图片
File outFile = new File("out.png");
ImageIO.write(image, "png", outFile);
} catch (Exception e) {
e.printStackTrace();
}
图片叠加示例:
图片压缩
/**
* 图片压缩
*
* @param imgsrc 原图地址
* @param imgdist 压缩后地址
* @param widthdist 宽
* @param heightdist 高
*/
public static void reduceImg(String imgsrc, String imgdist, int widthdist, int heightdist) {
try {
File srcfile = new File(imgsrc);
if (!srcfile.exists()) {
return;
}
Image src = javax.imageio.ImageIO.read(srcfile);
BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
// tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_AREA_AVERAGING), 0, 0, null);
FileOutputStream out = new FileOutputStream(imgdist);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
reduceImg("out.png", "111.png", 300, 300);
}
图片压缩示例
压缩前
压缩后