CutImage java实现

来源:互联网 发布:ifashion淘宝什么意思 编辑:程序博客网 时间:2024/06/06 11:42
import java.awt.image.BufferedImage;import java.io.*;import javax.imageio.*;import java.awt.*;public class CutImage {    public boolean cutImage(File sourceImage,String saveImagePath)    {        try{            // 获取底图            BufferedImage source=ImageIO.read(sourceImage);            int width=(int)(source.getWidth()*1.0/2);            int height=(int)(source.getHeight()*1.0/2);            // 切割成四个小图            for(int i=0;i<=1;i++) {                for (int j = 0; j <= 1; j++) {                    ImageIO.write(source.getSubimage(j * width, i * height, width, height), "JPEG", new File(saveImagePath + "\\cutImage_" + i + "" + j + ".jpg"));                }            }            // 获取小图            BufferedImage cutImg00 = ImageIO.read(new File("E:\\codes\\cutImage_00.jpg"));            BufferedImage cutImg01 = ImageIO.read(new File("E:\\codes\\cutImage_01.jpg"));            BufferedImage cutImg10 = ImageIO.read(new File("E:\\codes\\cutImage_10.jpg"));            BufferedImage cutImg11 = ImageIO.read(new File("E:\\codes\\cutImage_11.jpg"));            //创建一个不带透明度的图片            BufferedImage reverse10=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);            BufferedImage reverse11=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);            //像素取反            for (int i = 0; i < height; i++) {                for (int j = 0; j < width; j++) {                    int pixel = cutImg10.getRGB(j, i);                    reverse10.setRGB(j,i,0xFFFFFF-pixel);                }            }            for (int i = 0; i < height; i++) {                for (int j = 0; j < width; j++) {                    int pixel = cutImg11.getRGB(j, i);                    reverse11.setRGB(j,i,0xFFFFFF-pixel);                }            }            // 创建Graphics2D对象,用在底图对象上绘图            Graphics2D g2d = source.createGraphics();            // 在图形和图像中实现混合和透明效果,alpha选择值从0.0~1.0: 完全透明~完全不透明            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, (float) 1.0));            // 绘制 x:距离左上角的X偏移量  y:距离左上角的Y偏移量            g2d.drawImage(cutImg00, width, height, width, height, null);            g2d.drawImage(cutImg01, 0, 0, width, height, null);            g2d.drawImage(reverse10, width, 0, width, height, null);            g2d.drawImage(reverse11, 0, height, width, height, null);            g2d.dispose();// 释放图形上下文使用的系统资源            ImageIO.write(source, "JPEG", new File(saveImagePath + "\\TranformImage" + ".jpg"));            return true;        } catch (IOException e) {            e.printStackTrace();            return false;        }    }    public static void main(String[] args)    {        CutImage imageCutdemo=new CutImage();        if(imageCutdemo.cutImage(new File("E:\\codes\\eg.jpg"),"E:\\codes"))        {            System.out.println("转换成功");        }        else        {            System.out.println("转换失败");        }    }}
原创粉丝点击