Search code examples
javajpegencode

encoding jpeg in java without disk writing


as the title say i need to find some java jpeg encoder (it's good both source code or external library) that given an array that represent a raw pixel image or a BufferedImage can encode it without writing anything on file and return the encoded image possibly trough an array of some kind, with at least possibility to choose image quality and possibly with good efficiency.

NB: the array/image type input required (byte, int, argb, rgb, bgr, yuv...) doesn't matter for me, i can make approppriate conversions


Solution

  • As already mentioned in the comments: You can use the ImageIO class, and use it to write to a ByteArrayOutputStream. The code could really be as simple as this:

    private static byte[] getJpgData(BufferedImage image)
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", baos);
        return baos.toByteArray();
    }
    

    This will NOT write the image to a disc or so. It will only write the image into a memory block, which you can then process or manipulate further.