Java 如何准备设置像素的数组?

Java 如何准备设置像素的数组?,java,arrays,image,pixels,Java,Arrays,Image,Pixels,文件说: 如果我正在制作类型的缓冲图像: 这4个字节与INT数组的映射是什么?我尝试了各种组合,如0xff0000,0x00ff0000,等等,但都没有得到任何颜色 所有其他类型,如INT\u ARGB、BYTE\u BINARY等,是否有映射图?您的INT[]应包含0xFF0000(红色)、0x00FF00(绿色)、0x0000FF(蓝色)等值 下面是一个示例,它将生成具有各种颜色的3x3像素图像 根据图像类型,您可能需要添加对波段遮罩的更多支持 PixelWriterApp 像素书写器 Ar

文件说:

如果我正在制作类型的缓冲图像:

这4个字节与INT数组的映射是什么?我尝试了各种组合,如
0xff0000
0x00ff0000
,等等,但都没有得到任何颜色


所有其他类型,如
INT\u ARGB
BYTE\u BINARY
等,是否有映射图?

您的
INT[]
应包含
0xFF0000
(红色)、
0x00FF00
(绿色)、
0x0000FF
(蓝色)等值

下面是一个示例,它将生成具有各种颜色的3x3像素图像

根据图像类型,您可能需要添加对波段遮罩的更多支持

PixelWriterApp 像素书写器 ArrayUtils
奇怪,但这似乎是一个解决办法

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class ImageTesting2 extends JPanel{
    static  final int dim=20;
    static  int[] pixels = new int[dim*dim*4];
    BufferedImage image;

    public static void main(String[] args){

        ImageTesting2 tester = new ImageTesting2(); 
        tester.fillMatrix();
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(100, 100, 500, 500);
        frame.setVisible(true);
        frame.add(tester);
    }

     public void fillMatrix(){
            for(int i =0 ; i <pixels.length ; i=i+4){
               pixels[i] =255;     // red component
               pixels[i+1] = 0;    // green component
               pixels[i+2] = 255;  // blue component
               pixels[i+3] = 70;   // alpha component
            }

        image = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB);          
        WritableRaster raster =  image.getRaster();
        raster.setPixels(0,0,dim,dim,pixels);

   }     

    @Override
    public void paintComponent(Graphics g) {
           Graphics2D g2 = (Graphics2D) g;
           g2.drawImage(image, 50, 50, this);
    }  


}
导入java.awt.Graphics;
导入java.awt.Graphics2D;
导入java.awt.image.buffereImage;
导入java.awt.image.WritableRaster;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
公共类ImageTesting2扩展了JPanel{
静态最终int dim=20;
静态int[]像素=新int[dim*dim*4];
缓冲图像;
公共静态void main(字符串[]args){
ImageTesting2测试仪=新的ImageTesting2();
tester.fillMatrix();
JFrame=新JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
机架立根(100100500500);
frame.setVisible(true);
框架。添加(测试仪);
}
公共空间填充矩阵(){

对于(int i=0;i Ok,我刚刚意识到,如果我想制作一个sqare 10x10,我需要一个300字段的数组,否则它将成为ArrayIndexOutOfBoundsException。我是否需要将每个颜色组件放在数组的单独int中,然后将其加载到WritableRaster.setPixels()中?您可能需要一个大小为WIDTH*HEIGHT*BANDS的数组(3是RGB)生成最终的数组大小。是的,似乎是这样。通过实验,我得到了相同的结果。尽管一个INT可以在光栅中保存所有RGB或ARGB值(是吗?),但如果我想设置像素()光栅的颜色我需要为每个组件准备单独的整数,顺便说一句,最大值为255。另一件奇怪的事情是它似乎是一个R,G,B,一个类型为_ARGB的数组。“似乎是一个解决方案。”:什么问题的解决方案??你的问题是什么???只有你清楚地理解它所说的内容-如何准备颜色数据写入数组,然后将其发送给setPixel方法用于以后的图像渲染。这不再重要了。文档没有帮助,但我经过反复尝试。这是一个公平的评论,@Cornelius。这个hel谢谢,谢谢。
BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
import java.awt.Image;
import java.awt.image.*;
import java.io.*;
import java.nio.file.Paths;
import javax.imageio.ImageIO;

public class PixelWriterApp {
    public static int[] pixelData = {
        0xFF0000,  0xFF7F00,  0xFFFF00,
        0x00FF00,  0x00FF7F,  0x00FFFF,
        0x0000FF,  0x7F00FF,  0xFF00FF
    };

    public static void main(String[] args) {
        int cols = 3;
        int rows = pixelData.length / cols;
        int scaleX = 100;
        int scaleY = 100;
        int width = cols * scaleX;
        int height = rows * scaleY;
        int[] stretched = ArrayUtils.stretch(pixelData, cols, scaleX, scaleY);
        String directory = System.getProperty("user.home");
        String filename = "MyImage.png";
        String filepath = Paths.get(directory, filename).toString();
        int imageType = BufferedImage.TYPE_INT_RGB;
        Image image = PixelWriter.getImageFromArray(stretched, width, height, imageType);

        writeImage(image, filepath, "png");
    }

    public static void writeImage(Image image, String filename, String ext) {
        try {
            ImageIO.write((RenderedImage) image, ext, new File(filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.util.Arrays;

public class PixelWriter {
    private static final int[] BAND_COUNT_3 = { 0xFF0000, 0xFF00, 0xFF };
    private static final int[] BAND_COUNT_4 = { 0xFF0000, 0xFF00, 0xFF, 0xFF000000 };

    // See note about ARGB bands http://stackoverflow.com/a/25184537
    protected static int[] lookupBandMask(int imageType) throws IllegalArgumentException {
        switch (imageType) {
            case BufferedImage.TYPE_INT_RGB:
            case BufferedImage.TYPE_INT_BGR:
                return Arrays.copyOf(BAND_COUNT_3, BAND_COUNT_3.length);
            case BufferedImage.TYPE_INT_ARGB:
                return Arrays.copyOf(BAND_COUNT_4, BAND_COUNT_4.length);
        }
        throw new IllegalArgumentException("Unsupported BufferedImage type");
    }

    public static Image getImageFromArray(int[] pixels, int width, int height, int imageType) {
        int[] bandMasks = lookupBandMask(imageType);
        BufferedImage image = new BufferedImage(width, height, imageType);
        DataBufferInt buffer = new DataBufferInt(pixels, pixels.length);
        WritableRaster raster = Raster.createPackedRaster(buffer, width, height, width, bandMasks, null);
        image.setData(raster);
        return image;
    }
}
public class ArrayUtils {
    // Source: http://stackoverflow.com/a/16556564
    public static int[][] stretch(int[][] arr, int cfactor, int rfactor) {
        int rows = arr.length * rfactor;
        int cols = arr[0].length * cfactor;
        int[][] result = new int[rows][cols];
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                result[r][c] = arr[r / rfactor][c / cfactor];
            }
        }
        return result;
    }

    public static int[] stretch(int[] arr, int cols, int cfactor, int rfactor) {
        int rows = arr.length / cols;
        int width = cols * cfactor;
        int height = rows * rfactor;
        int[] result = new int[width * height];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                result[(y * height) + x] = arr[((y / rfactor) * rows) + (x / cfactor)];
            }
        }
        return result;
    }
}
// Image type is not recognized so it must be a customized image. This type is only used as a return value for the getType() method.
public static final int TYPE_CUSTOM = 0;

// Represents an image with 8-bit RGB color components packed into integer pixels. The image has a DirectColorModel without alpha. When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the java.awt.AlphaComposite documentation.
public static final int TYPE_INT_RGB = 1;

// Represents an image with 8-bit RGBA color components packed into integer pixels. The image has a DirectColorModel with alpha. The color data in this image is considered not to be premultiplied with alpha. When this type is used as the imageType argument to a BufferedImage constructor, the created image is consistent with images created in the JDK1.1 and earlier releases.
public static final int TYPE_INT_ARGB = 2;

// Represents an image with 8-bit RGBA color components packed into integer pixels. The image has a DirectColorModel with alpha. The color data in this image is considered to be premultiplied with alpha.
public static final int TYPE_INT_ARGB_PRE = 3;

// Represents an image with 8-bit RGB color components, corresponding to a Windows- or Solaris- style BGR color model, with the colors Blue, Green, and Red packed into integer pixels. There is no alpha. The image has a DirectColorModel. When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the java.awt.AlphaComposite documentation.
public static final int TYPE_INT_BGR = 4;

// Represents an image with 8-bit RGB color components, corresponding to a Windows-style BGR color model) with the colors Blue, Green, and Red stored in 3 bytes. There is no alpha. The image has a ComponentColorModel. When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the java.awt.AlphaComposite documentation.
public static final int TYPE_3BYTE_BGR = 5;

// Represents an image with 8-bit RGBA color components with the colors Blue, Green, and Red stored in 3 bytes and 1 byte of alpha. The image has a ComponentColorModel with alpha. The color data in this image is considered not to be premultiplied with alpha. The byte data is interleaved in a single byte array in the order A, B, G, R from lower to higher byte addresses within each pixel.
public static final int TYPE_4BYTE_ABGR = 6;

// Represents an image with 8-bit RGBA color components with the colors Blue, Green, and Red stored in 3 bytes and 1 byte of alpha. The image has a ComponentColorModel with alpha. The color data in this image is considered to be premultiplied with alpha. The byte data is interleaved in a single byte array in the order A, B, G, R from lower to higher byte addresses within each pixel.
public static final int TYPE_4BYTE_ABGR_PRE = 7;

// Represents an image with 5-6-5 RGB color components (5-bits red, 6-bits green, 5-bits blue) with no alpha. This image has a DirectColorModel. When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the java.awt.AlphaComposite documentation.
public static final int TYPE_USHORT_565_RGB = 8;

// Represents an image with 5-5-5 RGB color components (5-bits red, 5-bits green, 5-bits blue) with no alpha. This image has a DirectColorModel. When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the java.awt.AlphaComposite documentation.
public static final int TYPE_USHORT_555_RGB = 9;

// Represents a unsigned byte grayscale image, non-indexed. This image has a ComponentColorModel with a CS_GRAY java.awt.color.ColorSpace. When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the java.awt.AlphaComposite documentation.
public static final int TYPE_BYTE_GRAY = 10;

// Represents an unsigned short grayscale image, non-indexed). This image has a ComponentColorModel with a CS_GRAY ColorSpace. When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the java.awt.AlphaComposite documentation.
public static final int TYPE_USHORT_GRAY = 11;

// Represents an opaque byte-packed 1, 2, or 4 bit image. The image has an IndexColorModel without alpha. When this type is used as the imageType argument to the BufferedImage constructor that takes an imageType argument but no ColorModel argument, a 1-bit image is created with an IndexColorModel with two colors in the default sRGB ColorSpace: {0, 0, 0} and {255, 255, 255}. Images with 2 or 4 bits per pixel may be constructed via the BufferedImage constructor that takes a ColorModel argument by supplying a ColorModel with an appropriate map size. Images with 8 bits per pixel should use the image types TYPE_BYTE_INDEXED or TYPE_BYTE_GRAY depending on their ColorModel. When color data is stored in an image of this type, the closest color in the colormap is determined by the IndexColorModel and the resulting index is stored. Approximation and loss of alpha or color components can result, depending on the colors in the IndexColorModel colormap.
public static final int TYPE_BYTE_BINARY = 12;

// Represents an indexed byte image. When this type is used as the imageType argument to the BufferedImage constructor that takes an imageType argument but no ColorModel argument, an IndexColorModel is created with a 256-color 6/6/6 color cube palette with the rest of the colors from 216-255 populated by grayscale values in the default sRGB ColorSpace. When color data is stored in an image of this type, the closest color in the colormap is determined by the IndexColorModel and the resulting index is stored. Approximation and loss of alpha or color components can result, depending on the colors in the IndexColorModel colormap.
public static final int TYPE_BYTE_INDEXED = 13;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class ImageTesting2 extends JPanel{
    static  final int dim=20;
    static  int[] pixels = new int[dim*dim*4];
    BufferedImage image;

    public static void main(String[] args){

        ImageTesting2 tester = new ImageTesting2(); 
        tester.fillMatrix();
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(100, 100, 500, 500);
        frame.setVisible(true);
        frame.add(tester);
    }

     public void fillMatrix(){
            for(int i =0 ; i <pixels.length ; i=i+4){
               pixels[i] =255;     // red component
               pixels[i+1] = 0;    // green component
               pixels[i+2] = 255;  // blue component
               pixels[i+3] = 70;   // alpha component
            }

        image = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB);          
        WritableRaster raster =  image.getRaster();
        raster.setPixels(0,0,dim,dim,pixels);

   }     

    @Override
    public void paintComponent(Graphics g) {
           Graphics2D g2 = (Graphics2D) g;
           g2.drawImage(image, 50, 50, this);
    }  


}