java 图片 白边,如何在Java中自动裁剪图像白色边框?

What's the easiest way to auto crop the white border out of an image in java? Thanks in advance...

解决方案

If you want the white parts to be invisible, best way is to use image filters and make white pixels transparent, it is discussed here by @PhiLho with some good samples,

if you want to resize your image so it's borders won't have white colors, you can do it with four simple loops,

this little method that I've write for you does the trick, note that it just crop upper part of image, you can write the rest,

private Image getCroppedImage(String address) throws IOException{

BufferedImage source = ImageIO.read(new File(address)) ;

boolean flag = false ;

int upperBorder = -1 ;

do{

upperBorder ++ ;

for (int c1 =0 ; c1 < source.getWidth() ; c1++){

if(source.getRGB(c1, upperBorder) != Color.white.getRGB() ){

flag = true;

break ;

}

}

if (upperBorder >= source.getHeight())

flag = true ;

}while(!flag) ;

BufferedImage destination = new BufferedImage(source.getWidth(), source.getHeight() - upperBorder, BufferedImage.TYPE_INT_ARGB) ;

destination.getGraphics().drawImage(source, 0, upperBorder*-1, null) ;

return destination ;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现图片缩略并补白边,可以使用JavaJava 2D API。下面是一个简单的实现代码,其包括了图片缩略和补白边的功能。 ```java import java.awt.*; import java.awt.image.BufferedImage; public class ImageUtils { public static BufferedImage resizeAndPad(BufferedImage image, int newWidth, int newHeight) { // 计算宽高比例 double widthRatio = (double) newWidth / image.getWidth(); double heightRatio = (double) newHeight / image.getHeight(); double ratio = Math.min(widthRatio, heightRatio); // 计算缩略图大小 int width = (int) (image.getWidth() * ratio); int height = (int) (image.getHeight() * ratio); // 创建缩略图 BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = resizedImage.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.drawImage(image, 0, 0, width, height, null); g2d.dispose(); // 创建带有白色边框图片 BufferedImage paddedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB); g2d = paddedImage.createGraphics(); g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, newWidth, newHeight); g2d.drawImage(resizedImage, (newWidth - width) / 2, (newHeight - height) / 2, null); g2d.dispose(); return paddedImage; } } ``` 使用方法: ```java BufferedImage image = ImageIO.read(new File("image.jpg")); BufferedImage thumbnail = ImageUtils.resizeAndPad(image, 200, 200); ImageIO.write(thumbnail, "jpg", new File("thumbnail.jpg")); ``` 这里的 `resizeAndPad` 方法接受一个 `BufferedImage` 对象和两个整数参数,表示缩略图的宽度和高度。该方法会计算缩略图的大小,并创建带有白色边框的缩略图。最终返回带有白色边框的缩略图 `BufferedImage` 对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值