Java如何将像素数组转换为RGB单通道独立图片并存储
实现思路
每个存储在int数组中的像素值为ARGB格式,共4字节,从高位到低位依次对应:
- 8位alpha透明度通道
- 8位红色通道
- 8位绿色通道
- 8位蓝色通道
提取单通道图像的核心逻辑是:遍历所有像素,仅保留目标通道的色值,将其余两个颜色通道的值置为0,保留不透明alpha值,最终将处理后的像素数组写入新的图片文件即可。
完整实现代码
import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.image.ImageObserver; import java.awt.image.PixelGrabber; import java.io.File; import java.io.IOException; public class BMPtoArray { public static int[] convertToPixels(Image img) { int width = img.getWidth(null); int height = img.getHeight(null); int[] pixel = new int[width * height]; PixelGrabber pg = new PixelGrabber(img, 0, 0, width, height, pixel, 0, width); try { pg.grabPixels(); } catch (InterruptedException e) { throw new IllegalStateException("Error: Interrupted Waiting for Pixels"); } if ((pg.getStatus() & ImageObserver.ABORT) != 0) { throw new IllegalStateException("Error: Image Fetch Aborted"); } return pixel; } // 单通道图片生成并存储通用方法 private static void saveChannelImage(int[] pixels, int width, int height, int channelMask, String outputPath) throws IOException { BufferedImage channelImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int i = 0; i < pixels.length; i++) { // 保留alpha通道为不透明,仅保留目标通道色值,其余通道置0 int processedPixel = 0xFF000000 | (pixels[i] & channelMask); int x = i % width; int y = i / width; channelImage.setRGB(x, y, processedPixel); } ImageIO.write(channelImage, "bmp", new File(outputPath)); } public static void main(String[] args) throws IOException { // 读取原图 File inputFile = new File("C:\\Users\\Mhamd\\Desktop\\3rd year first semester\\Analysis and Coding\\labs\\2.2Java\\src\\circleRGB.bmp"); BufferedImage image = ImageIO.read(inputFile); int width = image.getWidth(); int height = image.getHeight(); // 获取像素数组 int[] pixels = convertToPixels(image); // 三个通道的掩码,分别对应红、绿、蓝 int redMask = 0x00FF0000; int greenMask = 0x0000FF00; int blueMask = 0x000000FF; // 输出路径默认和原图同目录,可自行修改 String parentPath = inputFile.getParent(); saveChannelImage(pixels, width, height, redMask, parentPath + File.separator + "red_circle.bmp"); saveChannelImage(pixels, width, height, greenMask, parentPath + File.separator + "green_circle.bmp"); saveChannelImage(pixels, width, height, blueMask, parentPath + File.separator + "blue_circle.bmp"); } }
代码说明
- 封装了
saveChannelImage通用方法,传入对应颜色通道的掩码即可生成对应单通道图片,避免重复代码 - 掩码
0x00FF0000对应红色通道,仅保留原像素的红色分量,绿色、蓝色分量会被置为0,以此类推对应绿色、蓝色的掩码 - 生成的三个单通道图片默认存储在原图所在目录,文件名分别为
red_circle.bmp、green_circle.bmp、blue_circle.bmp - 运行前请确认原图路径配置正确,对应目录有读写权限
内容的提问来源于stack exchange,提问作者Mohammed Hamdoon
相关产品推荐
相关产品推荐

