使用 JavaFX 将 BMP 加载到字节数组中

Posted

技术标签:

【中文标题】使用 JavaFX 将 BMP 加载到字节数组中【英文标题】:Loading BMP into byte array using JavaFX 【发布时间】:2020-05-16 08:40:23 【问题描述】:

我正在尝试使用 JavaFX 创建一个简单的位图类,它允许我加载、使用、修改位图并将其保存到文件中(用于科学模拟器)。我在将图像加载到字节数组时遇到问题。

1- 每个像素在缓冲区中需要 3 个字节的空间,我是否正确?

2- getPixels 函数收到以下异常:

java.lang.ClassCastException:类 javafx.scene.image.PixelFormat$ByteRgb 不能转换为类 javafx.scene.image.WritablePixelFormat(javafx.scene.image.PixelFormat$ByteRgb 和 javafx.scene.image.WritablePixelFormat 是在加载程序'app'的未命名模块中)

Intellij 建议转换为 (WritablePixelFormat)。我做错了什么?

3- 如何使用 getPixels 函数将整个图像加载到 RGB 整数的二维数组中? (使处理像素更容易)

谢谢。

public class BMP

    byte[] buffer;
    int width;
    int height;

    public BMP()
    
    

    public void load(String filename) throws FileNotFoundException
    
        //Creating an image
        Image image = new Image(new FileInputStream(filename));
        this.width = (int)image.getWidth();
        this.height = (int)image.getHeight();
        this.buffer = new byte[width * height * 3];

        //Reading color from the loaded image
        PixelReader pixelReader = image.getPixelReader();

        //Reading pixels of the image
        /*
        for(int y = 0; y < height; y++) 
            for(int x = 0; x < width; x++) 
                //Retrieving the color of the pixel of the loaded image
                Color color = pixelReader.getColor(x, y);
                System.out.println(color.toString());
            
        */

        pixelReader.getPixels(
                0,
                0,
                width,
                height,
                (WritablePixelFormat<ByteBuffer>) PixelFormat.getByteRgbInstance(),
                buffer,
                0,
                width * 3
        );
    

    public static void main(String[] args)
    
        BMP bmp1 = new BMP();

        try
        
            bmp1.load("e:/1.bmp");
            System.out.println("Width:"+ bmp1.width + " length:" + bmp1.height);
        
        catch (FileNotFoundException e)
        
            e.printStackTrace();
        
    

【问题讨论】:

【参考方案1】:

使用您加载的图像及其 PixelReader,您可以构建一个 WritableImage,它将为您提供一个 PixelWriter。这应该足以处理图像。我不会将其提取到数组中。

【讨论】:

以上是关于使用 JavaFX 将 BMP 加载到字节数组中的主要内容,如果未能解决你的问题,请参考以下文章

将 BMP 像素数据加载到数组 C 中

将字节数组转换/显示为 bmp/jpeg 图像

C++:.bmp 到文件中的字节数组

将Java位图转换为字节数组

使用字节数组 C++ 时出错

如何在java中从像素字节数组制作bmp图像