android如何截取图片的无效留白区域

该文章介绍了如何使用Java的ImageIO和BufferedImage类,通过getRGB方法分析图像,识别并裁剪出除白色和透明色之外的有效内容区域,实现图片的精确裁剪。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 调用ImageIO.read获取图片以及原图的宽度、高度
  2. 通过双层for循环获取黑色字所在矩阵的上下左右四个极值
  3. 调用BufferedImage 的getSubimage方法裁剪指定矩阵
  4. 调用ImageIO.write方法生成裁剪后的图片

使用getSubimage方法截取极值区域

		BufferedImage bufferedImage;
		try {
			bufferedImage = ImageIO.read(new File("/Users/macbookpro/Desktop/20231216-105805.png"));
			int width = bufferedImage.getWidth();
			int height = bufferedImage.getHeight();
			System.out.println("原图片宽度" + width);
			System.out.println("原图片高度" + height);
			int[] arr = bufferedImageToIntArray(bufferedImage, width, height);
			BufferedImage newBufferedImage = bufferedImage.getSubimage(arr[0], arr[1], arr[2], arr[3]);
			ImageIO.write(newBufferedImage, "png", new File("/Users/macbookpro/Desktop/test1.png"));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

下面这段代码可以获取到除白色和透明色之外,有效内容区的范围极值

	private static int whiteBg = new Color(255, 255, 255).getRGB();
	private static int transparentBg = new Color(0, 0, 0,0).getRGB();
	public static int[] bufferedImageToIntArray(BufferedImage image, int width, int height) {
		try {
			int rgb = 0;
			int x1 = width;
			int y1 = height;
			int x2 = 0;
			int y2 = 0;
			int temp1 = 0;
			int temp2 = 0;
			// 方式一:通过getRGB()方式获得像素数组
			for (int i = 0; i < width; i++) {
				for (int j = 0; j < height; j++) {
					rgb = image.getRGB(i, j);
					if (rgb != whiteBg&&rgb != transparentBg) {
						temp1 = i;
						temp2 = j;
						// 计算最左侧
						if (x1 >= temp1) {
							x1 = temp1;
						}
						// 计算最右侧
						if (x2 <= temp1) {
							x2 = temp1;
						}
						// 计算最下方
						if (y2 <= temp2) {
							y2 = temp2;
						}
						// 计算最上方
						if (y1 >= temp2) {
							y1 = temp2;
						}
					}
				}
			}
			return new int[] {x1, y1, x2 - x1, y2 - y1};
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值