Search code examples
javapngjpegjaipgm

java pgm 2 jpeg/png


I have an int array containing gray scale values from 0-254, i also have the x and y size of the image. It is an easy thing to create an pgm image, but i want to display it in a jsp, so i need somehow to convert it to a jpeg or png image. If you suggest jai, than please tell me at which classes to look, or how to actually do it in jai. Thanks a lot, in advance.


Solution

  • Maybe skip the PGM entirely?

    int[] myImage = getGreyscaleIntArray();
    
    BufferedImage im = new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);
    WritableRaster raster = im.getRaster();
    for(int h=0;h<height;h++)
    {
        for(int w=0;w<width;w++)
        {
            raster.setSample(w,h,0, myImage[h * width + w]); 
        }
    }
    
    ByteArrayOutputStream myJpg = new ByteArrayOutputStream();
    javax.imageio.ImageIO.write(im, "jpg", myJpg);
    

    uses the JAI ImageIO api, specifically the ImageIO utility class

    WriteableRaster sample from the Java Image Processing cookbook