java中的图片处理

图片本质上是一个存储了像素的数组,可以通过改变数组来对图片进行处理,下面是简单地通过图片获取数组的代码


class Image2Buff
{
	static byte[] image2Bytes(String imgSrc) throws Exception
	{
		FileInputStream fin = new FileInputStream(new File(imgSrc));
		//可能溢出,简单起见就不考虑太多,如果太大就要另外想办法,比如一次传入固定长度byte[]
		byte[] bytes  = new byte[fin.available()];
		//将文件内容写入字节数组,提供测试的case
		fin.read(bytes);
		fin.close();
		return bytes;
	}
}

class Buff2Image
{
	/**
	 @param b 传入的byte
	 @param tagSrc 目标文件名
		
	 */
	static void buff2Image(byte[] b,String tagSrc) throws Exception
	{
		FileOutputStream fout = new FileOutputStream(tagSrc);
		//将字节写入文件
		fout.write(b);
		fout.close();
	}
}

//本质上实现了copy 命令
public class fielzip
{
	public static void main(String[] args) throws Exception
	{
		//先模拟一个图形byte[]
		byte[] b = Image2Buff.image2Bytes("D:/test/2.jpg");
		//存为文件
		Buff2Image.buff2Image(b,"D:/test/3.jpg");

		System.out.println("Hello World!");
	}
}
上面只是利用图片获取图片的像素信息,下面是对图片中的像素进行处理的代码


 public class fielzip {
		 public static void main(String[] args) {
				OutputStream output = null;
				try {
					BufferedImage img = ImageIO.read(new File("D:/test/src.jpg"));
					int imageType = img.getType();
					int w = img.getWidth();
					int h = img.getHeight();
					int startX = 0;
					int startY = 0;
					int offset = 0;
					int scansize = w;
					// rgb的数组
					int[] rgbArray = new int[offset + (h - startY) * scansize
							+ (w - startX)];
					img.getRGB(startX, startY, w, h, rgbArray, offset, scansize);

					int x0 = w / 2;
					int y0 = h / 2;
					int rgb = rgbArray[offset + (y0 - startY) * scansize
							+ (x0 - startX)];
					Color c = new Color(rgb);
					System.out.println("中间像素点的rgb:" + c);
					// create and save to bmp
					File out = new File("D:/test/2.jpg");
					if (!out.exists())
						out.createNewFile();
					output = new FileOutputStream(out);
					BufferedImage imgOut = new BufferedImage(w, h, imageType);
					imgOut.setRGB(startX, startY, w, h, rgbArray, offset, scansize);
					ImageIO.write(imgOut, "bmp", output);
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (output != null)
						try {
							output.close();
						} catch (IOException e) {
						}
				}
			}

	 }


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值