Saturday, 3 February 2018

Converting image from File to byte array





    private byte[] image2byte(File file, String mimeType) {
                if (!mimeType.contains("image")) {
                    return null;
                }

                byte[] imageByte = null;
                String formatName = getFormatName(mimeType);


                BufferedImage bi;
                try {
                    bi = ImageIO.read(file);

                    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
                        boolean done = ImageIO.write(bi, formatName, baos);

                        baos.flush();

                        imageByte = baos.toByteArray();
                    }

                } catch (IOException ex) {
                    logger.error(ex.getMessage());
                }
                return imageByte;
            }





OR
 

    try {
            // Write the image to a buffer
            imagebuffer = new ByteArrayOutputStream();
            ImageIO.write(image, "png", imagebuffer);

            // Return a stream from the buffer
            return new ByteArrayInputStream(
                imagebuffer.toByteArray());
        } catch (IOException e) {
            return null;
        }


No comments:

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...