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

This my code: (updated)

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;

}

my photo:

vCdDn.jpg

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.

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?

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

A680y.jpgvC5Ck.jpg

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;

}

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值