有时候项目中会对图片进行操作,像切图啦,二值化啦,灰度啦。。
在验证码识别的时候很有用
现在将java对图片操作的部分方法写下来
不管图片如何操作,关键是在new BufferImage 时候的 TYPE
BufferedImage.TYPE_BYTE_GRAY 是灰度化
BufferedImage.TYPE_BYTE_BINARY 是二值化
BufferedImage.TYPE_INT_ARGB ........
详细参数介绍如下:
(1) 将地址转换为BufferImage
public static BufferedImage console(String imgUrl) { BufferedImage img = null; try { if (imgUrl.startsWith("http:")) { img = ImageIO.read(new URL(imgUrl)); } else { img = ImageIO.read(new File(imgUrl)); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return img; }
(2) 图片的灰度化:
public static void huiDuHua(BufferedImage img) { int sWight = img.getWidth(); int sHight = img.getHeight(); BufferedImage newImage = new BufferedImage(sWight, sHight, BufferedImage.TYPE_BYTE_GRAY); for (int x = 0; x < sWight; x++) { for (int y = 0; y < sHight; y++) { int rgb= img.getRGB(x, y); newImage.setRGB(x, y, rgb); } } try { ImageIO.write(newImage, "jpg", new File("aa.jpg")); } catch (IOException e) { e.printStackTrace(); } }
(3) 图片二值化
public static void erZhiHua(BufferedImage img) { int sWight = img.getWidth(); int sHight = img.getHeight(); BufferedImage newImage = new BufferedImage(sWight, sHight, BufferedImage.TYPE_BYTE_BINARY); for (int x = 0; x < sWight; x++) { for (int y = 0; y < sHight; y++) { int rgb= img.getRGB(x, y); newImage.setRGB(x, y, rgb); } } try { ImageIO.write(newImage, "jpg", new File("bb.jpg")); } catch (IOException e) { e.printStackTrace(); } }
(4)图片切割
public static BufferedImage cat(int x, int y, int wight, int hight, BufferedImage img) { int[] simgRgb = new int[wight * hight]; img.getRGB(x, y, wight, hight, simgRgb, 0, wight); BufferedImage newImage = new BufferedImage(wight, hight, BufferedImage.TYPE_INT_ARGB); newImage.setRGB(0, 0, wight, hight, simgRgb, 0, wight);// try {// ImageIO.write(newImage, "PNG", new File("aa.png"));// } catch (IOException e) {// // TODO Auto-generated catch block// e.printStackTrace();// } return newImage; }