RGB数据:int[]数组和byte[]数组的转化、图片转为RGB数据

字节数组中,每三个byte转为一个int。byte[]转int[]代码如下:

private int[] rgb24ToPixel(byte[] rgb24, int width, int height) {
        int[] pix = new int[rgb24.length / 3];
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                int idx = width * i + j;
                int rgbIdx = idx * 3;
                int red = rgb24[rgbIdx];
                int green = rgb24[rgbIdx + 1];
                int blue = rgb24[rgbIdx + 2];
                int color = (blue & 0x000000FF) | (green << 8 & 0x0000FF00) | (red << 16 & 0x00FF0000);
                pix[idx] = color;
            }
        }
        return pix;
    }

 int数组中,每一个int转为三个byte。代码如下:

private byte[] pixelToRgb24(int[] pix, int width, int height){
        byte[] rgb24 = new byte[width * height * 3];
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                int idx = width * i + j;
                int color = pix[idx]; //获取像素
                int red = ((color & 0x00FF0000) >> 16);
                int green = ((color & 0x0000FF00) >> 8);
                int blue = color & 0x000000FF;

                int rgbIdx = idx * 3;
                rgb24[rgbIdx] = (byte) red;
                rgb24[rgbIdx + 1] = (byte) green;
                rgb24[rgbIdx + 2] = (byte) blue;
            }
        }
        return rgb24;
    }

图片转为RGB数据:

private ImageInfo loadTestImage(String path) throws Exception {
    BufferedImage image = ImageIO.read(new File(path));
    if (image == null) {
        return null;
    }

    final int width = image.getWidth();
    final int height = image.getHeight();
    int[] pix = new int[width * height];
    PixelGrabber pg = new PixelGrabber(image, 0, 0, width, height, pix, 0, width);
    if (!pg.grabPixels()) {
        return null;
    }

    ImageInfo imageInfo = new ImageInfo();
    imageInfo.setWidth(width);
    imageInfo.setHeight(height);
    byte[] rgb24 = pixelToRgb24(pix,width,height);
    imageInfo.setImage(rgb24);
    return imageInfo;
}
class ImageInfo {
    int width;
    int height;
    byte[] rgb;
} 

RGB存储为图片:

public void rgbBytesToJpg(byte[] rgb,int width,int height,String path) throws IOException {
    BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    bufferedImage.setRGB(0,0,width,height,rgb24ToPix(rgb,width,height),0,width);
    File file = new File(path);
    ImageIO.write(bufferedImage, "jpg", file);
}

如果对您有用的话赞一下呗!谢谢!

发布了78 篇原创文章 · 获赞 131 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/river66/article/details/89514816