`
Dikaros
  • 浏览: 3384 次
文章分类
社区版块
存档分类
最新评论

几个java的图片方法

 
阅读更多

之前学校有个图片处理研究性学习,正好学了java高级,自己找了些资料写了几个图像处理的方法,在这里分享给大家

1、获取指定路径的图片

/**
	 * 读取指定路径的图片
	 * 
	 * @param path
	 *            图片路径
	 * @return 缓冲图片
	 */
	public static BufferedImage readPicture(String path) {
		try {
			// 使用Io流读取指定路径的图片将其存入图片流 抛出 FuleNotFoundException 以及IoException
			BufferedImage image = ImageIO.read(new FileInputStream(path));
			bImage = image;
			System.out.println("图片读取成功");
		} catch (FileNotFoundException e) {
			System.out.println("没有找到指定的图片");
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}

		return bImage;
	}


2、读取网络图片

/**
	 * 读取网络图片
	 * 
	 * @param url
	 *            地址
	 * @return 缓冲图片
	 */
	public static BufferedImage readWebImage(String url) {
		BufferedImage bf = null;
		HttpURLConnection conn;
		InputStream inStream = null;
		// 以流的方式获取网络数据
		try {
			URL u = new URL(url);
			conn = (HttpURLConnection) u.openConnection();
			// 设置请求方式为"GET"
			conn.setRequestMethod("GET");
			// 超时响应时间为5秒
			conn.setConnectTimeout(5 * 1000);
			// 通过输入流获取图片数据
			inStream = conn.getInputStream();
			bf = ImageIO.read(inStream);

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			// 关闭输入流释放连接

			if (inStream != null) {
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			conn = null;

		}

		return bf;
	}


3、使用BufferedImage创建一张图片

/**
	 * 使用图片流创建一张图片
	 * 
	 * @param bf
	 *            图片流
	 * @param path
	 *            路径
	 * @param name
	 *            文件名
	 * @param format
	 *            格式
	 */
	public static void creatPicture(BufferedImage bf, String path, String name,
			String format) {
		try {
			// 新建文件
			File file = new File(path + "/" + name + "." + format);
			// 通过图片io流将图片写入file文件
			ImageIO.write(bf, format, file);
			System.out.println("图片创建成功,保存在" + path + "/" + name + "目录下");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("创建失败");
		}

	}


4、获取色差,即颜色在直方图中的距离

/**
	 * 获取两个颜色的距离
	 * 
	 * @param r1
	 *            颜色1
	 * @param r2
	 *            颜色2
	 * @return 颜色距
	 */
	public static float getDistance(RGB r1, RGB r2) {
		// 结果
		float result = 0;
		// 使用空间两点间距离公式求解颜色距离
		result = (float) Math.sqrt(Math.pow(r1.getRed() - r2.getRed(), 2)
				+ Math.pow(r1.getGreen() - r2.getGreen(), 2)
				+ Math.pow(r1.getBlue() - r2.getBlue(), 2));
		return result;
	}


5、将一张彩色图片转换为灰度图

/**
	 * 全灰度图转换
	 * 
	 * @param path
	 *            图片路径
	 * @param type
	 *            0:hsv取亮度 1:RGB取平均值 2:移位算法 3。取红色 4。 取绿色 5.取蓝色 其他:RGB心理算法
	 * @param threshold
	 *            误差
	 */
	public static BufferedImage changeToGray(BufferedImage pixes, int type,
			int threshold) {
		BufferedImage bi = pixes;
		if (pixes.getHeight() < 1) {
			return bi;
		} else {

			Graphics2D g2 = (Graphics2D) bi.getGraphics();
			// i是纵坐标
			switch (type) {
			case 0:
				for (int i = 0; i < pixes.getHeight(); i++) {
					// j是横坐标
					for (int j = 0; j < pixes.getWidth(); j++) {
						// 获取颜色集合中一个颜色的int值
						RGB color = new RGB(pixes.getRGB(j, i));
						HSV hsv = color.toHSV();
						hsv.setSaturation(0);
						hsv.setHue(0);
						g2.setColor(new Color(color.toRGBInt()));
						if (getDistance(color, hsv.toRGB()) <= threshold) {
							g2.setColor(new Color(hsv.toRGB().toRGBInt()));
						}
						// System.out.println(g2.getColor());
						// 画一个像素
						g2.drawLine(j, i, j, i);
					}
				}

				break;

			case 1:
				for (int i = 0; i < pixes.getHeight(); i++) {
					// j是横坐标
					for (int j = 0; j < pixes.getWidth(); j++) {
						// 获取颜色集合中一个颜色的int值
						RGB color = new RGB(pixes.getRGB(j, i));
						int ave = (color.getBlue() + color.getRed() + color
								.getGreen()) / 3;
						g2.setColor(new Color(color.toRGBInt()));
						if (getDistance(color, new RGB(ave, ave, ave)) <= threshold) {
							g2.setColor(new Color(ave, ave, ave));
						}
						// System.out.println(g2.getColor());
						// 画一个像素
						g2.drawLine(j, i, j, i);
					}
				}
				break;

			case 2:
				for (int i = 0; i < pixes.getHeight(); i++) {
					// j是横坐标
					for (int j = 0; j < pixes.getWidth(); j++) {
						// 获取颜色集合中一个颜色的int值
						RGB color = new RGB(pixes.getRGB(j, i));
						int ave = (color.getBlue() * 28 + color.getRed() * 76 + color
								.getGreen() * 151) >> 8;
						g2.setColor(new Color(color.toRGBInt()));
						if (getDistance(color, new RGB(ave, ave, ave)) <= threshold) {
							g2.setColor(new Color(ave, ave, ave));
						}
						// System.out.println(g2.getColor());
						// 画一个像素
						g2.drawLine(j, i, j, i);
					}
				}
				break;
			case 3:
				for (int i = 0; i < pixes.getHeight(); i++) {
					// j是横坐标
					for (int j = 0; j < pixes.getWidth(); j++) {
						// 获取颜色集合中一个颜色的int值
						RGB color = new RGB(pixes.getRGB(j, i));
						g2.setColor(new Color(color.toRGBInt()));
						if (getDistance(
								color,
								new RGB(color.getRed(), color.getRed(), color
										.getRed())) <= threshold) {
							g2.setColor(new Color(color.getRed(), color
									.getRed(), color.getRed()));
						}

						// System.out.println(g2.getColor());
						// 画一个像素
						g2.drawLine(j, i, j, i);
					}
				}
				break;
			case 4:
				for (int i = 0; i < pixes.getHeight(); i++) {
					// j是横坐标
					for (int j = 0; j < pixes.getWidth(); j++) {
						// 获取颜色集合中一个颜色的int值
						RGB color = new RGB(pixes.getRGB(j, i));
						g2.setColor(new Color(color.toRGBInt()));
						if (getDistance(color,
								new RGB(color.getGreen(), color.getGreen(),
										color.getGreen())) <= threshold) {
							g2.setColor(new Color(color.getGreen(), color
									.getGreen(), color.getGreen()));
						}

						// System.out.println(g2.getColor());
						// 画一个像素
						g2.drawLine(j, i, j, i);
					}
				}
				break;
			case 5:
				for (int i = 0; i < pixes.getHeight(); i++) {
					// j是横坐标
					for (int j = 0; j < pixes.getWidth(); j++) {
						// 获取颜色集合中一个颜色的int值
						RGB color = new RGB(pixes.getRGB(j, i));
						g2.setColor(new Color(color.toRGBInt()));
						if (getDistance(
								color,
								new RGB(color.getBlue(), color.getBlue(), color
										.getBlue())) <= threshold) {
							g2.setColor(new Color(color.getBlue(), color
									.getBlue(), color.getBlue()));
						}

						// System.out.println(g2.getColor());
						// 画一个像素
						g2.drawLine(j, i, j, i);
					}
				}
				break;
			default:
				for (int i = 0; i < pixes.getHeight(); i++) {
					// j是横坐标
					for (int j = 0; j < pixes.getWidth(); j++) {
						// 获取颜色集合中一个颜色的int值
						RGB color = new RGB(pixes.getRGB(j, i));
						int gray = (color.getBlue() * 114 + color.getRed()
								* 299 + color.getGreen() * 587) / 1000;
						g2.setColor(new Color(color.toRGBInt()));
						if (getDistance(color, new RGB(gray, gray, gray)) <= threshold) {
							g2.setColor(new Color(gray, gray, gray));
						}

						// System.out.println(g2.getColor());
						// 画一个像素
						g2.drawLine(j, i, j, i);
					}
				}
				break;
			}

			return bi;
		}
	}
其中出现的RGB类是色彩的RGB格式,HSV是色彩的HSV格式

RGB.java

public class RGB {
	// 红色
	private int red;
	// 绿色
	private int green;
	// 蓝色
	private int blue;

	/**
	 * 默认生成白色
	 */
	public RGB() {
		red = 255;
		green = 255;
		blue = 255;
	}

	/**
	 * 用RGB值初始化一个颜色
	 * 
	 * @param red
	 *            红色值 0-255
	 * @param green
	 *            绿色值 0-255
	 * @param blue
	 *            蓝色值 0-255
	 */
	public RGB(int red, int green, int blue) {
		if (red < 256 && green >= 0 && green < 256 && green >= 0 && blue < 256
				&& blue >= 0) {
			this.red = red;
			this.green = green;
			this.blue = blue;
		} else {
			this.red = 0;
			this.green = 0;
			this.blue = 0;
		}
	}

	/**
	 * 使用32位整型值初始化一个颜色
	 * 
	 * @param color
	 *            例如 0xffffff -1
	 */
	public RGB(int color) {
		// Color类 可以使用整形值初始化一个类,由于
		Color c = new Color(color);
		red = c.getRed();
		green = c.getGreen();
		blue = c.getBlue();
	}

	public int getRed() {
		return red;
	}

	public void setRed(int red) {
		this.red = red;
	}

	public int getGreen() {
		return green;
	}

	public void setGreen(int green) {
		this.green = green;
	}

	public int getBlue() {
		return blue;
	}

	public void setBlue(int blue) {
		this.blue = blue;
	}

	/**
	 * 转换为32位整型值 用于初始化一个Color对象
	 * 
	 * @return 32位整型
	 */
	public int toRGBInt() {
		int rgb = 0xff000000 | (red << 16) | green << 8 | blue;
		return rgb;

	}

	public float getDistance(RGB rgb) {
		return (float) Math.sqrt(Math.pow(this.getRed() - rgb.getRed(), 2)
				+ Math.pow(this.getGreen() - rgb.getGreen(), 2)
				+ Math.pow(this.getBlue() - rgb.getBlue(), 2));

	}

	/**
	 * RGB转HSV算法
	 * 
	 * @return
	 */
	public HSV toHSV() {
		int hue = 0;// 色调
		int saturation = 0;// 饱和度
		int value = 0;// 亮度

		int max = Math.max(Math.max(red, blue), green);
		int min = Math.min(Math.min(red, blue), green);

		// 色调的计算
		if (max == min) {
			hue = 0;
		} else {
			if (max == red && green >= blue) {
				hue = (int) ((green - blue) / (float) (max - min) * 60);
			} else if (max == red && green < blue) {
				hue = (int) ((green - blue) / (float) (max - min) * 60 + 360);

			} else if (max == green) {
				hue = (int) ((blue - red) / (float) (max - min) * 60 + 120);

			} else if (max == blue) {
				hue = (int) ((red - green) / (float) (max - min) * 60 + 240);
			}
		}

		value = max;// 亮度的值为颜色最大值
		if (max == 0) {
			saturation = 0;
		} else {
			saturation = (int) ((float) (max - min) / max * 100);// 饱和度计算
		}

		return new HSV(hue, saturation, value);

	}

	public String toString() {
		return "[" + red + "," + green + "," + blue + "]";

	}


HSV.java

public class HSV {
	int hue;// 色调0-360
	int saturation;// 饱和度0-100
	int value;// 亮度0-255

	public HSV() {
		this.hue = 0;
		this.saturation = 0;
		this.value = 0;
	}
	/**
	 * 使用参数初始化HSV信息
	 * @param hue 色调
	 * @param saturation 饱和度
	 * @param value 亮度
	 */
	public HSV(int hue, int saturation, int value) {
		if (hue <= 360 && saturation >= 0 && saturation <= 100
				&& value >= 0 && value <= 255) {
			this.hue = hue;
			this.saturation = saturation;
			this.value = value;
		} else {
			this.hue = 0;
			this.saturation = 0;
			this.value = 0;
		}

	}

	public int getHue() {
		return hue;
	}

	public void setHue(int hue) {
		this.hue = hue;
	}

	public int getSaturation() {
		return saturation;
	}

	public void setSaturation(int saturation) {
		this.saturation = saturation;
	}

	public int getValue() {
		return value;
	}

	public void setValue(int value) {
		this.value = value;
	}

	public String toString(){
		return "["+hue+","+saturation+","+value+"]";
	}
	/**
	 * HSV转RGB算法
	 * @return
	 */
	public RGB toRGB() {
		int red = 0;
		int green = 0;
		int blue = 0;

		float a, b, c, h;//

		if (saturation == 0) {
			red = value;
			green = value;
			blue = value;
		} else {
			h = hue / (float) 60;
			int i = hue / 60;
			
			a = (float) (value * (100 - saturation)/100.0);
			b = (float) (value * (100 - saturation * (h-i))/100.0);
			c = (float) (value * (100 - saturation* (1 - h+i))/100.0);
			switch (i) {

			case 0:
				red=value;
				green=Math.round(c);
				blue=Math.round(a);
				break;
			case 1:
				red=Math.round(b);
				green=value;
				blue=Math.round(a);
				break;
			case 2:
				red=Math.round(a);
				green=value;
				blue=Math.round(c);
				break;
			case 3:
				red=Math.round(a);
				green=Math.round(b);
				blue=value;
				break;
			case 4:
				red=Math.round(c);
				green=Math.round(a);
				blue=value;
				break;
			case 5:
				red=value;
				green=Math.round(a);
				blue=Math.round(b);
				break;
			}

		}

		return new RGB(red, green, blue);
	}

}


6、在一张图片上的指定位置用指定颜色画一个矩形

/**
	 * 在一张图片上的指定位置用指定颜色画一个矩形
	 * 
	 * @param pix
	 *            图片流
	 * @param x
	 *            起点 横坐标
	 * @param y
	 *            起点 纵坐标
	 * @param width
	 *            矩形宽度
	 * @param height
	 *            矩形高度
	 * @param rgb
	 *            画笔颜色
	 * @return 画完方后的矩形
	 */
	public static BufferedImage drawRectOnMip(BufferedImage pix, int x, int y,
			int width, int height, RGB rgb) {
		BufferedImage pixes = pix;
		if (x > pixes.getWidth() || y > pixes.getHeight()
				|| width > pixes.getWidth() - x
				|| height > pixes.getHeight() - y) {
			System.out.println("无法绘制");
			return pix;
		}
		// pic_drawRect

		Graphics2D g2 = (Graphics2D) pixes.getGraphics();
		for (int i = 0; i < pixes.getHeight(); i++) {
			// j是横坐标
			for (int j = 0; j < pixes.getWidth(); j++) {
				// 获取颜色集合中一个颜色的int值
				Color color = new Color(pixes.getRGB(j, i));
				// System.out.println(pixes.get(i).get(j).toRGBInt());
				// System.out.println(color);
				g2.setColor(color);
				// System.out.println(g2.getColor());
				// 画一个像素
				g2.drawLine(j, i, j, i);

			}
		}
		g2.setColor(new Color(rgb.toRGBInt()));
		g2.drawRect(x, y, width, height);
		return pixes;
	}



版权声明:本文为博主原创文章,未经博主允许不得转载。

分享到:
评论

相关推荐

    java实现二维码生成的几个方法

    java实现二维码生成的几个方法,文中分析二维码的生成原理,编码方式及二维码的解析方式。

    利用Java程序把多张图片合成一张图片

    利用Java程序把多张图片合成一张图片,利用Java程序把多张图片合成一张图片。

    java实现对图片的压缩上传

    该工具类可以实现以下几个功能 1、得到有效文件的长度(即大小),以字节表示 getFileSize(String filePath),需要传入文件路径 2、可以上传图片与非图片文件。有二个重构方法 一、无限制文件大小上传upLoad(String...

    Java将多张图片合成为一张图像.rar

    Java将多张图片合成为一张,类似于PhotoShop中的合成图片,将两张图片合成输出为一张JPG,两幅图像叠加在一起,这是个比较基础的Java图像合成的例子。在JAVA中实现图片合成,本例的实现核心代码如下:  InputStream...

    一个Java Applet的动态显示图片的小程序

    简单的一个Java Applet的动态显示图片的小程序。将资源内的图片放置到E盘根目录下。如果想换图片,记得修改width和heigh的初始值,值为图片的宽和高。如果你对动画有兴趣,可以试着稍微修改一下本程序(程序里有相关...

    java图片特效处理过滤器

    javajava图片特效处理程序,有几十种特效,包括水波纹、高斯模糊、浮雕效果等等,里面有html说明和一个测试程序,自己可以根据需要更改调试。

    [原创] 高清晰高品质Java图片压缩

    但是有一个缺点,可能也是java的缺点吧,呵呵。 &lt;br&gt;在jdk1.6以下的版本环境下,压缩部分图片会很慢,经过我测试,如果图片的DPI越高,速度越慢,一般WEB使用图片DPI都是72,速度很快。大家可以试下。我测试了几...

    java开源包5

    Java Remote Desktop 是一个Java 的远程桌面软件,支持很多特性例如文件传输、数据压缩、颜色转换、键盘鼠标事件转换等等。 最短路径算法实现 k-shortest-paths 这是一个实现了 Yen 的排名算法的无环路径的项目 ...

    基于Java-Web技术的图片管理系统的设计与实现.doc

    基于Java Web技术的图片管理系统 的设计与实现 本科毕业设计 目 录 第1章 引言 6 1.1 课题研究目的及意义 6 1.2 课题研究的内容 7 2.1 用户功能需求 7 图片收藏数据库查询系统图片收藏数据库查询系统是方便用户对...

    Java PDF转图片 完美方案 绝对可用

    基于apache pdfbox库实现Java PDF转图片,带源码和pom文件; 开发环境导入maven工程,PdfToImg为测试类,修改其中test.pdf和test.png的路径即可运行; PDFUtil为独立工具类,可放置任何工程中运行。 如果在linux...

    JAVA上百实例源码以及开源项目

     util实现Java图片水印添加功能,有添加图片水印和文字水印,可以设置水印位置,透明度、设置对线段锯齿状边缘处理、水印图片的路径,水印一般格式是gif,png,这种图片可以设置透明度、水印旋转等,可以参考代码...

    JAVA上百实例源码以及开源项目源代码

     util实现Java图片水印添加功能,有添加图片水印和文字水印,可以设置水印位置,透明度、设置对线段锯齿状边缘处理、水印图片的路径,水印一般格式是gif,png,这种图片可以设置透明度、水印旋转等,可以参考代码...

    java生成word,包括word表格,表格插入图片,jar包都在了

    第一次传的时候少了实体类,这次代码传全了,连jar包都给大家准备好了,jar包导入WebRoot的WEB-INF的lib下三个类全部导入,自己准备几张图片,取好名字放在D盘,就可以用了

    Java编写的扫雷小程序--图片

    ShowNum 监听到某个button后,计算出此button周围有几个雷,不同的雷对应不通的图片,此类得到button上应加载的图片地址 ViewReSet 此类用于新建一个窗口,用户输入自己想要的行、列、雷数,然后用新的行列雷数new一...

    java开源包6

    Java Remote Desktop 是一个Java 的远程桌面软件,支持很多特性例如文件传输、数据压缩、颜色转换、键盘鼠标事件转换等等。 最短路径算法实现 k-shortest-paths 这是一个实现了 Yen 的排名算法的无环路径的项目 ...

    java开源包11

    Java Remote Desktop 是一个Java 的远程桌面软件,支持很多特性例如文件传输、数据压缩、颜色转换、键盘鼠标事件转换等等。 最短路径算法实现 k-shortest-paths 这是一个实现了 Yen 的排名算法的无环路径的项目 ...

    java开源包9

    Java Remote Desktop 是一个Java 的远程桌面软件,支持很多特性例如文件传输、数据压缩、颜色转换、键盘鼠标事件转换等等。 最短路径算法实现 k-shortest-paths 这是一个实现了 Yen 的排名算法的无环路径的项目 ...

    java开源包101

    Java Remote Desktop 是一个Java 的远程桌面软件,支持很多特性例如文件传输、数据压缩、颜色转换、键盘鼠标事件转换等等。 最短路径算法实现 k-shortest-paths 这是一个实现了 Yen 的排名算法的无环路径的项目 ...

    java开源包4

    Java Remote Desktop 是一个Java 的远程桌面软件,支持很多特性例如文件传输、数据压缩、颜色转换、键盘鼠标事件转换等等。 最短路径算法实现 k-shortest-paths 这是一个实现了 Yen 的排名算法的无环路径的项目 ...

    人脸识别检测opencv简单java实现

    人脸识别检测opencv简单java实现要不是毕业好几年我都不舍得分享出来!!! CTRL+D收藏一下或者关注走一波-有你所需!不断更新! 其他相关下载,配套代码以及PPT。稳妥的小老弟 ...加载本地的OpenCV库,这样就可以用它...

Global site tag (gtag.js) - Google Analytics