Java下BufferedImage处理PNG图片的ARGB

通过MultipartFile传入png图片,并通过BufferedImage进行处理。

@SneakyThrows
public void picture(MultipartFile multipartFile) {
    //读取图片
    System.out.println("正在读取...");
    BufferedImage bufferedImage = null;
    try {
        bufferedImage = ImageIO.read(multipartFile.getInputStream());
    } catch (Exception e) {
        e.printStackTrace();
    }
    int width = bufferedImage.getWidth();
    int height = bufferedImage.getHeight();
    int minx = bufferedImage.getMinX();
    int miny = bufferedImage.getMinY();
    //处理图片
    System.out.println("正在处理...");
    for (int i = minx; i < width; i++) {
        for (int j = miny; j < height; j++) {
            int pixel = bufferedImage.getRGB(i, j);//获取颜色
            int alpha = pixel >> 24 & 0xff;//获取alpha
            int red = pixel & 0xff0000 >> 16;//获取红色
            int green = pixel & 0xff00 >> 8;//获取绿色
            int blue = pixel & 0xff;//获取蓝色
            int color = (alpha << 24) | (red << 16) | (green << 8) | blue;//将argb还原成整数
            bufferedImage.setRGB(i, j, color);//设置颜色
        }
    }
    //保存图片
    File file = new File("test.png");
    ImageIO.write(bufferedImage, "png", file);
    System.out.println("处理完毕...");
}

 

posted on 2021-05-01 14:31  chenyangsocool  阅读(1035)  评论(0编辑  收藏  举报