java 對圖片進行切割,灰度化,切割操作


有時候項目中會對圖片進行操作,像切圖啦,二值化啦,灰度啦。。

在驗證碼識別的時候很有用

現在將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;
    }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM