Auf Thema antworten

Eventuell hilft Dir noch dies:


Ich habe meine Klasse einmal etwas umgeschrieben und JavaDoc Kommentare hinzu gefügt. Evtl. wird die so direkt nutzbar. (Dann ggf. das package umändern und einfach 1:1 nutzen.) Ist ein 08/15 Code daher ohne irgendwelche Lizenz direkt verwendbar / änderbar.


Aber ist alles noch ungetestet - habe jetzt keine Zeit gehabt, den Unit-Test anzupassen. Sollte etwas nicht funktionieren, dann bitte einmal Bescheid geben.


[CODE=java]package de.kneitzel.images;


import javax.imageio.ImageIO;

import java.awt.*;

import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.InputStream;


/**

* Helper class to scale images

*/

public class ImageScaler {


    /**

     * Target format to use for all generated images.

     */

    private static String TARGET_FORMAT="png";


    /**

     * Creates a new scaled image.

     * <p>

     *     The image is scaled with keeping the original ratio from width to height.

     * <p>

     *     If enforceSize is false, the given size is used as a possible maximum size. The target picture might be

     *     smaller if the ratio height to width given is different to the ratio of the original image.

     *     If enforceSize is true, the new image can have a transparent arew on top/bottom or

     *     right/left side.

     * @param originalImageBytes Bytes of the original image.

     * @param width (Maximum) Width of the target image.

     * @param height (Maximum) Height of the target image.

     * @param enforceSize Should the size be enforced. If false, the target image will not have empty borders on top/bottom or right/left.

     * @return Byte Array with the new image or null in case an error occured.

     */

    public static byte[] createScaledImage(final byte[] originalImageBytes, final int width, final int height, final boolean enforceSize) {

        // Validation

        if (originalImageBytes == null) return null;

        if (originalImageBytes.length==0) return null;


        try {

            // Create the image from a byte array.

            BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(originalImageBytes));

            return createScaledImage(originalImage, width, height, enforceSize);

        } catch (Exception ex) {

            return null;

        }

    }


    /**

     * Scales an image to a new size.

     * <p>

     *     If enforceSize is false, the given size is used as a possible maximum size. The target picture might be

     *     smaller if the ratio height to width given is different to the ratio of the original image.

     *     If enforceSize is true, the new image can have a transparent arew on top/bottom or

     *     right/left side.

     * @param originalImageBytes Bytes of the original image.

     * @param width (Maximum) Width of the target image.

     * @param height (Maximum) Height of the target image.

     * @param enforceSize Should the size be enforced. If false, the target image will not have empty borders on top/bottom or right/left.

     * @return InputStream for the new image or null if a new image couldn't be created.

     */

    public static InputStream scaledImage(final byte[] originalImageBytes, final int width, final int height, final boolean enforceSize) {

        // Get the scaled image.

        byte[] bytes = createScaledImage(originalImageBytes, width, height, enforceSize);


        // Validation of result.

        if (bytes == null || bytes.length == 0) return null;


        // Return new InputStream.

        return new ByteArrayInputStream(bytes);

    }


    /**

     * Creates the scaled image of a BufferedImage.

     * <p>

     *     If enforceSize is false, the given size is used as a possible maximum size. The target picture might be

     *     smaller if the ratio height to width given is different to the ratio of the original image.

     *     If enforceSize is true, the new image can have a transparent arew on top/bottom or

     *     right/left side.

     * @param originalImage Original image to scale.

     * @param width (Maximum) Width of the target image.

     * @param height (Maximum) Height of the target image.

     * @param enforceSize Should the size be enforced. If false, the target image will not have empty borders on top/bottom or right/left.

     * @return Byte Array with the new image or null in case an error occured.

     */

    protected static byte[] createScaledImage(final BufferedImage originalImage, final int width, final int height, final boolean enforceSize) {

        // Validation

        if (originalImage == null) return null;


        try {

            // Get the scale factor.

            double scaleWidth = (double) width / (double) originalImage.getWidth();

            double scaleHeight = (double) height / (double) originalImage.getHeight();


            double scaleFactor;

            if (scaleWidth > scaleHeight) {

                scaleFactor = scaleHeight;

            } else {

                scaleFactor = scaleWidth;

            }


            // Calculate target size of scaled image.

            int newHeight = (int) (scaleFactor * originalImage.getHeight());

            int newWidth = (int) (scaleFactor * originalImage.getWidth());


            // Cooordinates of new picture and size of new picture.

            int x, y, usedHeight, usedWidth;

            if (enforceSize) {

                usedHeight = height;

                usedWidth = width;

                x = (width - newWidth) / 2;

                y = (height - newHeight) / 2;

            } else {

                x = 0;

                y = 0;

                usedHeight = newHeight;

                usedWidth = newWidth;

            }


            // Scale the image

            BufferedImage scaledImage = new BufferedImage(usedWidth, usedHeight, BufferedImage.TYPE_INT_ARGB);

            Graphics2D graphics = scaledImage.createGraphics();

            graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

            graphics.drawImage(originalImage, x, y, newWidth, newHeight, null);


            // Get the bytes of the image

            try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {

                ImageIO.write(scaledImage, TARGET_FORMAT, stream);

                return stream.toByteArray();

            }

        } catch (Exception ex) {

            return null;

        }

    }

}[/CODE]



Oben