如何在Java中裁剪图像? [英] How to crop image in java?

查看:246
本文介绍了如何在Java中裁剪图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java来上传文件时裁剪图像,我设置了值并尝试裁剪,但是没有得到我期望的正确图像大小

I'm using java to crop image when upload file, I set value and to try to crop but is not get correct size of image as I expected

这我的代码:(已更新

private BufferedImage cropImageSquare(byte[] image) throws IOException {        
    InputStream in = new ByteArrayInputStream(image);
    BufferedImage originalImage = ImageIO.read(in);

    System.out.println("Original Image Dimension: "+originalImage.getWidth()+"x"+originalImage.getHeight());            

    BufferedImage croppedImage = originalImage.getSubimage(300, 150, 500, 500);
    System.out.println("Cropped Image Dimension: "+croppedImage.getWidth()+"x"+croppedImage.getHeight());


     return croppedImage;
}

我的照片:

我想将图像裁剪为上面的图像(红线),但是我的代码似乎不正确。

I want to crop image as above image (red line) but my code is seem incorrect.

如何按预期裁剪图像?

How to crop image as expect?

推荐答案


我想将图像裁剪为上面的图像(红线),但是我的代码似乎不正确。

I want to crop image as above image (red line) but my code is seem incorrect.

因此,您输入的图像为 1024x811 ,而您的目标图像是 928x690 ,大约是 0.906x0.8509 减少/差异-所以真正的问题是...哪一个

So, your input image is 1024x811 and your "target" image is 928x690, which is roughly 0.906x0.8509 reduction/difference - so the real question is ... which one of those is the right value?

通过我的测试,根据这张图片, 0.8509 产生了最好的结果

Through my testing, based on this image, 0.8509 produces the best result

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Test {

    public static void main(String[] args) throws IOException {
        BufferedImage crop = new Test().crop(0.8509);
        System.out.println(crop.getWidth() + "x" + crop.getHeight());
        ImageIO.write(crop, "jpg", new File("Square.jpg"));
    }

    public BufferedImage crop(double amount) throws IOException {
        BufferedImage originalImage = ImageIO.read(Test.class.getResource("Cat.jpg"));
        int height = originalImage.getHeight();
        int width = originalImage.getWidth();

        int targetWidth = (int)(width * amount);
        int targetHeight = (int)(height * amount);
        // Coordinates of the image's middle
        int xc = (width - targetWidth) / 2;
        int yc = (height - targetHeight) / 2;

        // Crop
        BufferedImage croppedImage = originalImage.getSubimage(
                        xc, 
                        yc,
                        targetWidth, // widht
                        targetHeight // height
        );
        return croppedImage;
    }

}

现在,这不做任何检查( xc + targetWidth> imageWidth ),但我确定您可以填写

Now, this doesn't do any checks (xc + targetWidth > imageWidth), but I'm sure you can fill that out

这篇关于如何在Java中裁剪图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆