开发者

java, picture resize

im having a problem with resizing pictures in java!

i get the pictures from an xml document but most of them are in landscape mode! i need to have them resized/converted into portrait mode so they fit into my GUI layout.

is there a method fo开发者_StackOverflow中文版r doing this??


You can scale width and height by the same value to get the image with a similar resolution.

But what you problem really is? How to scale or what?

I wrote this for scale both height and width by the same value based on the target width and height

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageTest {
    public static BufferedImage resize(int targetWidth, int targetHeight,
            BufferedImage src) {
        double scaleW = (double) targetWidth / (double) src.getWidth() ;
        double scaleH = (double) targetHeight / (double) src.getHeight() ;

        double scale = scaleW < scaleH ? scaleW : scaleH;

        BufferedImage result = new BufferedImage((int) (src.getWidth() * scale),
                (int) (src.getHeight() * scale), BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2d = result.createGraphics();
        g2d.drawImage(src, 0, 0, result.getWidth(), result.getHeight(), null);
        g2d.dispose();

        return result;
    }

    public static void main(String[] args) throws IOException {
        BufferedImage origin = ImageIO.read(new File(
                "/home/marcos/icons/print.png"));

        File dest = new File("/home/marcos/icons/print2.png");
        dest.createNewFile();
        ImageIO.write(resize(180, 200, origin), "PNG", dest);
    }
}


In order to convert a picture from landscape mode to portrait mode, without rotating, you first have to crop the picture. Then, you may have to reduce the size of the picture.

Let's say your landscape picture is 500 x 300 pixels, and you want your portrait picture to be 150 X 250 pixels.

You could crop the landscape picture to 180 X 300 pixels by cropping the center. Then you can reduce the cropped picture down to 150 x 250 pixels.

Here's some Java code for cropping an image:

    int x           = (videoWidth - imageWidth) / 2;
    int y           = (videoHeight - imageHeight) / 2;
    CropImageFilter cropFilter = new CropImageFilter
            (x, y, imageWidth, imageHeight);
    Image croppedImage = toolkit.createImage(new FilteredImageSource
            (image.getSource(), cropFilter));

image is a java.awt.Image, and toolkit is the default java.awt.Toolkit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜