圖片打水印 縮放 以及輸入流轉換

圖片打水印和縮放:

 public final static BufferedImage[] pressImage(InputStream srcImg, String waterImg,float alpha) throws IOException {
    	
    	 //File file = new File(targetImg);
        Image image = ImageIO.read(srcImg);
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufferedImage.createGraphics();
        g.drawImage(image, 0, 0, width, height, null);
    
        Image waterImage = ImageIO.read(new File(waterImg));    // 水印文件
        
        int width_1 = waterImage.getWidth(null);
        int height_1 = waterImage.getHeight(null);
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
        
        int div=(int) (0.1*width_1);
          
        for(int y=0,row=0;y<height;y+=height_1+div,row++)
        {
        	int x=0;
        	       	
            for(;x<width;x+=width_1+div)
            {              	
            	g.drawImage(waterImage, x, y, width_1, height_1, null); // 水印文件結束	                	
            }
        }             
        
        g.dispose();
        
        BufferedImage bufferedImage2=Thumbnails.of(bufferedImage).size(100, 100).asBufferedImage();
        
       
      
       return new BufferedImage[]{bufferedImage,bufferedImage2};
    	
    }

圖片的縮放使用了Thumbnails這個工具,(其實它也可以用來打水印的,不過我還沒有研究)

jar 包或者maven 請自行搜索

需要特別注意的是 Thumbnails 默認是按照等比例進行縮放的並且它的縮放規則是:

假設 把圖片所放到 200*300

* 若圖片橫比200小,高比300小,不變
* 若圖片橫比200小,高比300大,高縮小到300,圖片比例不變
* 若圖片橫比200大,高比300小,橫縮小到200,圖片比例不變
* 若圖片橫比200大,高比300大,圖片按比例縮小,橫爲200或高爲300

bufferInage轉換 inputSteam

private InputStream getInputstreamFromBufferedImage(BufferedImage img) throws IOException{
		 	ByteArrayOutputStream bs =new ByteArrayOutputStream();
		 	ImageOutputStream imOut =ImageIO.createImageOutputStream(bs);
	        ImageIO.write(img,"jpg",imOut); //scaledImage1爲BufferedImage,jpg爲圖像的類型
	        
	        InputStream is =new ByteArrayInputStream(bs.toByteArray());
	        return is;
		
	}



發佈了56 篇原創文章 · 獲贊 6 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章