Re[2]: Resize Image
От: n0name2  
Дата: 22.12.06 15:02
Оценка: 13 (3)
Здравствуйте, Blazkowicz, Вы писали:

B>http://java.sun.com/products/java-media/2D/reference/faqs/index.html#Q_How_do_I_create_a_resized_copy


Плохо этот код ресайзит (по крайней мере в меньшую сторону). Несмотря ни на какие хинты.
Долго мучался с этим, в конце концов нашел что можно сделать вот так:


    private static void rescale(@NotNull InputStream input, @NotNull OutputStream output, int tw, int th) throws IOException {
        // Create the image
        BufferedImage image = new BufferedImage(tw, th, BufferedImage.TYPE_INT_RGB);
        // Create the graphics
        Graphics2D graphics = image.createGraphics();
        try {
            // Set rendering hints
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            // Open the source image
            @NotNull BufferedImage source = ImageIO.read(input);
            // Get width & geight
            int w = source.getWidth(), h = source.getHeight();
            // Calculate the scale
            double scale = Math.min((double)tw/(double)w, (double)th/(double)h);
            // Calculate the coordinates
            int x = (int)(((double)tw - (double)w * scale) / 2.0d), y = (int)(((double)th - (double)h * scale) / 2.0d);
            // Get the scaled instance
            @NotNull Image scaled = source.getScaledInstance((int)(w * scale), (int)(h * scale), Image.SCALE_SMOOTH);
            // Set the color
            graphics.setColor(Color.WHITE);
            // Paint the white rectangle
            graphics.fillRect(0, 0, tw, th);
            // Draw the image
            graphics.drawImage(scaled, x, y, null);
        } finally {
            // Always dispose the graphics
            graphics.dispose();
        }
        // Write the rescaled image
        ImageIO.write(image, "png", output);
    }
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.