vahitdurmus
vahitdurmus

Reputation: 39

Convert to bytes from jpeg in java

I want to convert byte array from JPEG in Java. Below code makes wrong my request.

BufferedImage img=Image.read("C:\blabla");
WritableRaster raster=img.getRaster();
DataBufferByte buffer=(DataBufferByte)raster.getDataBuffer();
byte[] jpegbytes=buffer.getData();

When I execute it gives wrong byte number. JPEG has size 845.941 bytes on disk. But, it returns size 2 359 296 bytes in jpegbytes. How can I get to correct byte value? I think, BufferedImage class gets take wrong.

Upvotes: 2

Views: 1117

Answers (1)

Bruce Hamilton
Bruce Hamilton

Reputation: 560

You can write any file to a byte array by writing the contents of its FileInputStream to a ByteArrayOutputStream and calling toByteArray().

public byte[] fileToBytes(String filename) throws IOException {
    final byte[] buffer = new byte[256];
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        try (InputStream in = new FileInputStream(new File(filename))) {
            int bytesRead;
            while ((bytesRead = in.read(buffer)) > 0)
                out.write(buffer, 0, bytesRead);
        }
        return out.toByteArray();
    }
}

Upvotes: 2

Related Questions