简体   繁体   English

将数组转换为图像 Java

[英]Converting an array to image Java

I would like to convert an array of pixels to images so that I can read each pixel of the image, I've converted the image to pixels and now what I'm trying to do is that I have a picture of an RGB circle, After converting the image to pixels I want to draw images again but Not the entire picture again, I want to draw the red circle alone, the green circle alone and the blue circle alone and store the images in a file, how can that be done?我想将像素数组转换为图像,以便我可以读取图像的每个像素,我已经将图像转换为像素,现在我想要做的是我有一张 RGB 圆圈的图片,将图像转换为像素后,我想再次绘制图像但不是再次绘制整个图片,我想单独绘制红色圆圈,单独绘制绿色圆圈和单独绘制蓝色圆圈并将图像存储在文件中,怎么做?

Here's the code that I used to convert the image to array pixels:这是我用来将图像转换为数组像素的代码:

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;
}
public static void main(String[] args) throws IOException {
    BufferedImage image = ImageIO.read(new File("C:\\Users\\Mhamd\\Desktop\\3rd year 
first semester\\Analysis and Coding\\labs\\2.2Java\\src\\circleRGB.bmp"));
    //System.out.println(convertToPixels(image));
}
}

Here's the image:这是图像:

RGB圆

so this is basically what I'm trying to achieve所以这基本上就是我想要实现的目标

这就是我想要实现的

Here's a simple example of how to "turn off" the red channel:这是一个如何“关闭”红色通道的简单示例:

final BufferedImage image = ImageIO.read(new File("test.bmp"));
int red = 0x00FF0000;
for (int row = 0; row < image.getHeight(); row++) {
    for (int col = 0; col < image.getWidth(); col++) {
        int color = image.getRGB(col, row);
        color &= ~red;
        image.setRGB(col, row, color);
    }
}

This sets the red in each RGB pixel to 0. You can repeat for other colors and combinations.这会将每个 RGB 像素中的红色设置为 0。您可以对其他 colors 和组合重复此操作。

This produces this from your source image:这会从您的源图像中生成:

只是蓝色和绿色球的图片

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM