java - 从具有颜色强度的双数组创建图像

标签 java double bufferedimage

我有一个二维双数组,其中包含图像的颜色强度值,看起来与此类似(我的数组大小为 256x256,填充了如下值):

790.0 739.0 690.0 601.0 582.0 630.0 730.0 773.0
982.0 879.0 754.0 695.0 687.0 631.0 630.0 666.0
1046.0 1080.0 1070.0 990.0 872.0 730.0 647.0 657.0
1008.0 998.0 962.0 959.0 944.0 930.0 921.0 932.0

是否可以从此文件创建图像对象?

我当前的代码:

    Double imageLayer[][] = vtkLayers.get(layer);

    int xLenght = imageLayer.length;
    int yLength = imageLayer[0].length;

    System.out.println(xLenght);
    System.out.println(yLength);

    BufferedImage b = new BufferedImage(xLenght, yLength, 3);

    for(int x = 0; x < xLenght; x++) {
        for(int y = 0; y < yLength; y++) {
            int rgb = (imageLayer[x][y]).intValue() << 16 | (imageLayer[x][y]).intValue() << 8 | (imageLayer[x][y]).intValue();
            b.setRGB(x, y, rgb);
        }
    }
    try {
        File outputfile = new File("C:\\temp\\image.png");
        ImageIO.write(b, "png", outputfile);
    }
    catch (IOException e){
        System.out.println("Could not create picture");
    }

为了测试它,我尝试创建一个 png 文件。但这段代码目前只产生一个空白的 png 文件。 由于我是 Java 新手,我使用过 this作为指南发布。

如果我可以直接创建一个 Image 对象,而不需要先创建一个 png,那就最好了。

最佳答案

我可以自己解决这个问题:

        Double imageLayer[][] = vtkLayers.get(layer);

        // Initialize BufferedImage, assuming Color[][] is already properly populated.
        BufferedImage bufferedImage = new BufferedImage(imageLayer.length, imageLayer[0].length,
                BufferedImage.TYPE_INT_RGB);

        // Set each pixel of the BufferedImage to the color from the Color[][].
        for (int x = 0; x < imageLayer.length; x++) {
            for (int y = 0; y < imageLayer[x].length; y++) {
                Color test = doubleToColor(imageLayer[x][y], 4080);

                bufferedImage.setRGB(x, y, test.getRGB());
            }
        }

        try {
            File imageFile = new File(path);
            ImageIO.write(bufferedImage, "png", imageFile);
        }
        catch (Exception e){
            System.out.println("Failed to create image");
        }

函数 doubleToColor 将我的 double 转换为 RGB 代码:

    public static Color doubleToColor(double x,double maxx){
        float cR=(float)(0.5 + (x / (2 * maxx)));
        float cG=(float)(0.5 + (x / (2 * maxx)));
        float cB=(float)(0.5 - (x / (2 * maxx)));
        Color c = new Color(cR,cG,cB);
        return c;
    }

关于java - 从具有颜色强度的双数组创建图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59199332/

相关文章:

java - 计算器正在加法而不是减法

java - 在 Java 堆之外分配的巨大内存

java - 以双为键的 HashMap

java - 将多个 BufferedImages 添加到组件以进行拖动

java - 如何从包含像素的数组创建 BufferedImage?

java - 如何将 BufferedImage 转换/转换为图像?

java - 用 Guava 替换通用集合的兼容性问题

c - 字符串转换为数字 ( strtod ) 的问题

arrays - Swift 组合两个数组并对数组进行排序

java - 构建 war 时创建额外的 jar