JAVA 操作图片(改变尺寸、转黑白)参考一些文章自己整理使用工具类

该博客介绍了如何在Java中处理图片,包括根据操作系统获取临时文件路径,读取输入流,调整图片尺寸,以及将图片转换为黑白。使用了ImageUtils和ImageBlackUtil工具类,实现了图片的缩放、灰度处理和二值化操作。通过 Commons IO 库完成文件操作。

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

//获取到的输入流
InputStream inputStream = ···;
String path = "";
//判断当前系统的是win还是Linux或者其他
String os = System.getProperty("os.name");
if (os.toLowerCase().startsWith("win")) {
	path = bigDataConfig.getTmpDirWindows();
} else {
	path = bigDataConfig.getTmpDirLinux();
}
System.out.println("path:" + path);
// 生成导入的临时文件
File tempFile = new File(path, "visitorHeadPortrait_" + System.currentTimeMillis() + ".png");
FileUtils.copyInputStreamToFile(inputStream, tempFile);
ImageUtils.resizeImage(tempFile, 80, 120);
// String hexStr = ImageUtils.imageToBlackWhite(tempFile);
String hexStr = ImageBlackUtil.imageToBlackWhite(tempFile);
// 删除生成的临时文件
tempFile.delete();

调整图片大小

/**
	 * 调整图片尺寸
	 */
	public static void resizeImage(File srcFile, int width, int height) {
		Image srcImg;
		try {
			srcImg = ImageIO.read(srcFile);
			BufferedImage buffImg = null;
			buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			buffImg.getGraphics().drawImage(srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
			ImageIO.write(buffImg, "JPG", srcFile);

		} catch (IOException e) {
			System.out.println("图片转换出现异常!");
			e.printStackTrace();
		}
	}

图片转黑白(指定像素大小)

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

import javax.imageio.ImageIO;

public class ImageBlackUtil {

	public static String imageToBlackWhite(File file) throws IOException {
		byte[] result = new byte[1200];

		String resultStr = null;
		BufferedImage image = ImageIO.read(file);
		// 120*80
		int width = image.getWidth();
		int height = image.getHeight();
		// 重写图片
		// BufferedImage grayImage = new BufferedImage(width, height,
		// image.getType());
		// 灰度加权处理
		int[][] grayImageResult = imageGray(image);
		// 将灰度图片缩小4倍
		int[][] resizeImageResult = imageResize(grayImageResult);

		// 将图片进行放大处理4倍,得到01灰度图像
		int[][] imageResult = imageBigger(resizeImageResult);
		// 图片写出,将返回的1变成255
		// for(int i =0;i<grayImage.getHeight();i++) {
		// for(int j =0 ;j<grayImage.getWidth();j++) {
		// grayImage.setRGB(j, i, colorToRGB(0, imageResult[i][j],
		// imageResult[i][j], imageResult[i][j]));
		// }
		// }
		// ImageIO.write(grayImage, "jpg", new
		// File("F:/document/test/matlab.jpg"));
		// 将0,1按位存储
		for (int i = 0; i < height; i++) {
			for (int j = 0; j < width;) {
				byte temp = new Byte("0");
				for (int k = 0; k < 8; k++) {
					if (imageResult[i][j] == 1) {
						temp = (byte) (temp | (0x1 << (7 - k)));
					} else {
						temp = (byte) (temp | (0x0 << (7 - k)));
					}
					j++;
				}
				result[i * 10 + j / 8 - 1] = (byte) (temp & 0xff);
			}
		}
		resultStr = toHexString(result);
		return resultStr;
	}

	public static String toHexString(byte[] byteArray) {
		if (byteArray == null || byteArray.length < 1)
			throw new IllegalArgumentException("this byteArray must not be null or empty");

		final StringBuilder hexString = new StringBuilder();
		for (int i = 0; i < byteArray.length; i++) {
			if ((byteArray[i] & 0xff) < 0x10)// 0~F前面不零
				hexString.append("0");
			hexString.append(Integer.toHexString(0xFF & byteArray[i]));
		}
		return hexString.toString().toLowerCase();
	}
	
	/**
	 * 颜色分量转换为RGB值
	 * 
	 * @param alpha
	 * @param red
	 * @param green
	 * @param blue
	 * @return
	 */
	private static int colorToRGB(int alpha, int red, int green, int blue) {

		int newPixel = 0;
		newPixel += alpha;
		newPixel = newPixel << 8;
		newPixel += red;
		newPixel = newPixel << 8;
		newPixel += green;
		newPixel = newPixel << 8;
		newPixel += blue;
		return newPixel;
	}

	// 将图片进行放大处理4倍
	/**
	 * 
	 * @param resizeImageResult
	 */
	private static int[][] imageBigger(int[][] resizeImageResult) {
		// 2*2抖动矩阵
		int[][] baseArray = new int[][] { { 0, 2 }, { 3, 1 } };
		// 将灰度图像的灰度级限制在4以内
		int div = 256 / 4;
		// 01矩阵结果
		int height = resizeImageResult.length;
		int width = resizeImageResult[0].length;
		int[][] imageResult = new int[height * 2][width * 2];
		// 将灰度值限制在4内
		int[][] temp = new int[height][width];
		for (int i = 0; i < height; i++) {
			for (int j = 0; j < width; j++) {
				temp[i][j] = resizeImageResult[i][j] / div;
			}
		}
		// 放大4倍
		for (int i = 0; i < height; i++) {
			for (int j = 0; j < width; j++) {
				for (int p = 0; p < 2; p++) {
					for (int q = 0; q < 2; q++) {
						if (temp[i][j] > baseArray[p][q]) {
							imageResult[2 * i + p][2 * j + q] = 1;
						} else {
							imageResult[2 * i + p][2 * j + q] = 0;
						}
					}
				}
			}
		}
		return imageResult;
	}	

	// 将图片进行灰度处理 加权灰度,0.2989R+ 0.5870G + 0.1140B
	private static int[][] imageGray(BufferedImage image) {
		int width = image.getWidth();
		int height = image.getHeight();
		int[][] result = new int[height][width];
		for (int i = 0; i < height; i++) {
			for (int j = 0; j < width; j++) {
				int color = image.getRGB(j, i);
				final int r = (color >> 16) & 0xff;
				final int g = (color >> 8) & 0xff;
				final int b = color & 0xff;
				// 加权计算灰度
				double temp = 0.2989 * r + 0.5870 * g + 0.1140 * b;
				result[i][j] = (int) Math.round(temp);
			}
		}
		return result;
	}	

	// 将图片进行缩小1/2
	public static int[][] imageResize(int[][] image) {
		int height = image.length;
		int width = image[0].length;
		int[][] result = new int[height / 2][width / 2];
		for (int i = 0, p = 0; i < image.length; i = i + 2, p++) {
			for (int j = 0, q = 0; j < width; j = j + 2, q++) {
				result[p][q] = image[i][j];
			}
		}
		return result;
	}

	public static void main(String[] args) throws IOException {
		File file = new File("F:/document/test/7.jpg");
		String result = imageToBlackWhite(file);
		System.out.println(result);
	}

}

依赖jar

<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.7</version>
		</dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值