0

As the title suggest, I am trying to read and output a raw image file. My goal in this program is to read a raw image and do some image processing and then output the final image. I got an idea how to do this program but I am stuck trying to read a raw image in java. Im not even sure how to upload the raw image into my project folder properly. Any advice will be appreciated. Here is my code so far (granted I took this code from a website to test out).

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

public class Assignment_1 {

void importImageIGuess() {

}

public static void main(String[] args) throws IOException {
    int width = 512;
    int length = 512;
    BufferedImage image = null;
    File f = null;

    //Read File I guess
    try {
        f = new File("lena.raw");
        image = new BufferedImage(width, length, BufferedImage.TYPE_INT_ARGB);
        image = ImageIO.read(f);
        System.out.println("Reading completed");

    }
    catch(IOException e) {
        System.out.println("Error " +e);

    }
    try{
        f = new File("lenaOutput.raw");
        ImageIO.write(image, "raw", f);
        System.out.println("Writing completed I guess");


    } catch (IOException e ) {
        System.out.println("Error " + e);
    }

}

}

Brody Gore
  • 77
  • 2
  • 11

2 Answers2

2

ImageIO supports GIF, JPEG, PNG, BMP and WBMP, but you can find some libraries for RAWs as well (for example jrawio) as in ImageIO support for raw images (jrawio)

m.s
  • 39
  • 1
  • 5
2
int[] rgb = image.getRGB(0, 0, width, height, null, 0, width);

or

WritableRaster raster = image.getWritableRaster();

Admittedly getRGB is simpler. Above I assumed the scan size to be the width, sometimes it is aligned. RGBA, ARGB and one may vary.

It is a linearized one-dimensional array, one may use an IntBuffer, even change the byte order to little endian if so desired.

Path path = Paths.get("lena.raw");
byte[] content = Files.readAllBytes(path);
IntBuffer buf = ByteBuffer.wrap(content) /*.order(ByteOrder.LITTE_ENDIAN)*/ .asIntBuffer();
int[] rgb = new int[content.length / 4];
buf.get(rgb);
BufferedImage outImage = new BufferedImage(width, length, BufferedImage.TYPE_INT_ARGB);
outImage.setRGB(0, 0, width, height, rgb, 0, width);
ImageIO.write(outImage, "png", new FileOutputStream(...));

Also look into file channel and MappedByteBuffer for gain of speed and memory usage.

Probably the first time false colors are to be expected (TYPE_INT_ARGB).

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138