如何从2D数组写入灰度图像

时间:2015-06-23 08:23:01

标签: java image-processing

我想将灰度图像值读入2d数组,更改2d数组的值,并根据修改后的2d数组值创建新的灰度图像。

以下是将灰度图像读入2D数组(arr [] [])的代码。

package dct;

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.io.File;
import javax.imageio.ImageIO;

/**
 *
 * @author jain
 */
public class writeGR {

            public static void main(String[] args)
            {
                File file = new File("lightning.jpg");
                BufferedImage img = null;
                try
                {
                    img = ImageIO.read(file);
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }

                int width = img.getWidth();
                int height = img.getHeight();
                int[][] arr = new int[width][height];

                Raster raster = img.getData();

                for (int i = 0; i < width; i++)
                {
                    for (int j = 0; j < height; j++)
                    {
                        arr[i][j] = raster.getSample(i, j, 0);

                    }
                }

                BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
                image.setData(raster);
                //
                //BufferedImage image1 = image;
                try
                {
                    File ouptut = new File("grayscale.png");
                    ImageIO.write(image, "png", ouptut);
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }    

        }// main

}

现在我想更改“arr [] []”vlaues并创建一个新的灰度图像。怎么做?

1 个答案:

答案 0 :(得分:0)

上述问题可以通过以下代码解决:

                for(int i=0;i<width;i++)
                {
                    for(int j=0;j<height;j++)
                    {
                        tempArr[0] = 100;
                        raster1.setPixel(i, j, tempArr);
                    }
                }

                BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
                image.setData(raster1);

                try
                {
                    File ouptut = new File("change.png");
                    ImageIO.write(image, "png", ouptut);
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }