java讀取圖片色彩值(自動識別驗證碼)

來源:互聯網
上載者:User

讀取圖片的色彩值,是圖片識別的基礎邏輯。

 代碼如下 複製代碼

package com.javaer.image;
 
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
 
import javax.imageio.ImageIO;
 
public class ReadColor {
 /**
  * 讀取一張圖片的RGB值
  * @throws Exception
  */
 public void getImagePixel(String image) throws Exception {
  int[] rgb = new int[3];
  File file = new File(image);
  BufferedImage bi = null;
  try {
   bi = ImageIO.read(file);
  } catch (Exception e) {
   e.printStackTrace();
  }
  int width = bi.getWidth();
  int height = bi.getHeight();
  int minx = bi.getMinX();
  int miny = bi.getMinY();
  System.out.println("width=" + width + ",height=" + height + ".");
  System.out.println("minx=" + minx + ",miniy=" + miny + ".");
  for (int i = minx; i < width; i++) {
   for (int j = miny; j < height; j++) {
    int pixel = bi.getRGB(i, j); //下面三行代碼將一個數字轉換為RGB數字
    rgb[0] = (pixel & 0xff0000) >> 16;
    rgb[1] = (pixel & 0xff00) >> 8;
    rgb[2] = (pixel & 0xff);
     System.out.println("i="+i+",j="+j+":("+rgb[0]+","+rgb[1]+","+rgb[2]+")");
   }
  }
 }
 
 /**
  * 返回螢幕色彩值
  *
  * @param x
  * @param y
  * @return
  * @throws AWTException
  */
 public int getScreenPixel(int x, int y) throws AWTException { // 函數傳回值為顏色的RGB值。
  Robot rb = null; // java.awt.image包中的類,可以用來抓取螢幕,即截屏。
  rb = new Robot();
  Toolkit tk = Toolkit.getDefaultToolkit(); // 擷取預設工具包
  Dimension di = tk.getScreenSize(); // 螢幕尺寸規格
  System.out.println(di.width);
  System.out.println(di.height);
  Rectangle rec = new Rectangle(0, 0, di.width, di.height);
  BufferedImage bi = rb.createScreenCapture(rec);
  int pixelColor = bi.getRGB(x, y);
 
  return 16777216 + pixelColor; // pixelColor的值為負,經過實踐得出:加上顏色最大值就是實際顏色值。
 }
 
 /**
  * @param args
  */
 public static void main(String[] args) throws Exception {
  int x = 0;
  ReadColor rc = new ReadColor();
  x = rc.getScreenPixel(100, 345);
  System.out.println(x + " - ");
  rc.getImagePixel("/a.jpg");
 }
 
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.