Breite und Höhe eines Bildes in base64 auslesen

krgewb

Top Contributor
Wie bekomme ich die width und height? Mit normalen URLs habe ich es bereits geschafft. Mit base64-URLs funktioniert es aber noch nicht. Hier ist mein Code:
Java:
try {
    BufferedImage read = ImageIO.read(new URL("data:image/jpeg;base64," + requestDTO.getImage()));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(read, "jpg", baos);
    int widthOfImageWhenInFullSize = read.getWidth();
    int heightOfImageWhenInFullSize = read.getHeight();
    baos.close();
} catch (IOException e) {
    logger.error("error");
}
 
Das "data" URL-Scheme als Wert in einem img-Tag src-Attribute ist nur etwas, was der Browser versteht. Du müsstest also selbst erstmal den base64-kodierten Teil extrahieren, in binär umwandeln und dann z.B. als ByteArrayInputStream laden.
 
Danke! Das hat funktioniert! Hier ist der Code:

Java:
        try {
            BufferedImage read = decodeToImage(requestDTO.getImage());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(read, "jpg", baos);
            int widthOfImageWhenInFullSize = read.getWidth();
            int heightOfImageWhenInFullSize = read.getHeight();
            baos.close();
        } catch (IOException e) {

        }

decodeToImage:

Java:
    public static BufferedImage decodeToImage(String imageString) {

        BufferedImage image = null;
        byte[] imageByte;
        try {
            imageByte = Base64.getDecoder().decode(imageString);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
            image = ImageIO.read(bis);
            bis.close();
        } catch (Exception e) {

        }
        return image;
    }
 

Neue Themen


Zurück
Oben