天天看点

CutImage java实现

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()*/);
            int height=(int)(source.getHeight()*/);
            // 切割成四个小图
            for(int i=;i<=;i++) {
                for (int j = ; j <= ; 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 = ; i < height; i++) {
                for (int j = ; j < width; j++) {
                    int pixel = cutImg10.getRGB(j, i);
                    reverse10.setRGB(j,i,-pixel);
                }
            }
            for (int i = ; i < height; i++) {
                for (int j = ; j < width; j++) {
                    int pixel = cutImg11.getRGB(j, i);
                    reverse11.setRGB(j,i,-pixel);
                }
            }

            // 创建Graphics2D对象,用在底图对象上绘图
            Graphics2D g2d = source.createGraphics();
            // 在图形和图像中实现混合和透明效果,alpha选择值从0.0~1.0: 完全透明~完全不透明
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, (float) ));
            // 绘制 x:距离左上角的X偏移量  y:距离左上角的Y偏移量
            g2d.drawImage(cutImg00, width, height, width, height, null);
            g2d.drawImage(cutImg01, , , width, height, null);
            g2d.drawImage(reverse10, width, , width, height, null);
            g2d.drawImage(reverse11, , 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("转换失败");
        }
    }
}