Tony
Tony

Reputation: 111

ImageIO.write has invalid writer

Quarkus / JSF / Primefaces project.

I am trying to convert a resized image back to a byte array and I keep getting a false for the validWriter and, as such, the returned byte array is empty.

private byte[] createBytesFromImage(BufferedImage image, String contentType) {
        ByteArrayOutputStream baosToReturn = new ByteArrayOutputStream();
        try {
            boolean validWriter = ImageIO.write(image, contentType, baosToReturn);
            if (!validWriter) {
                logger.error("Not a Valid Writer");
            }
        } catch (IOException e) {
            baosToReturn = null;
            logger.error("Error trying to convert image " + e);
            e.printStackTrace();
        }
        return baosToReturn.toByteArray();
    }

Upvotes: 0

Views: 370

Answers (1)

Tony
Tony

Reputation: 111

AArrghhh.

Passing contentType (from the uploaded image) does not work.

You need to give the image a piece of text like "png"...

boolean validWriter = ImageIO.write(image, "png", baosToReturn);

Went with:

    // https://stackoverflow.com/questions/67081086/imageio-write-has-invalid-writer
    private byte[] createBytesFromImage(BufferedImage image, String contentType) {
        ByteArrayOutputStream baosToReturn = new ByteArrayOutputStream();
        String[] splitString = contentType.split("/");
        if (splitString.length == 0) {
            logger.error("++++++++++++++++++++++++++ content type cannot be split");
        } else {
            if (splitString.length != 2) {
                logger.error("++++++++++++++++++++++++++ content type cannot be split to two parts (e.g. image and png)");
            } else {
                logger.info("contentType is split down to " + splitString[0] + " and " + splitString[1]);
                if (!splitString[0].equalsIgnoreCase("image")) {
                    logger.error("++++++++++++++++++++++++++ content type first part is not image");
                } else {                    
                    try {
                        boolean validWriter = ImageIO.write(image, splitString[1], baosToReturn);
                        if (!validWriter) {
                            logger.error("Could not find a Valid Image Writer");
                        }
                    } catch (IOException e) {
                        baosToReturn = null;
                        logger.error("Error trying to convert image " + e);
                        e.printStackTrace();
                    }               
                }
            }
        }
        return baosToReturn.toByteArray();
    }
    

Upvotes: 1

Related Questions