1. 程式人生 > >生成圖片縮圖

生成圖片縮圖

複製程式碼
package com.ares.image.test;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

import javax.imageio.ImageIO; import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ares.slf4j.test.Slf4jUtil; /** * <p>Title: ImageUtil </p> * <p>Description: </p> * <p>Email:
[email protected]
</p> *
@author Ares * @date 2014年10月28日 上午10:24:26 */ public class ImageUtil { static { Slf4jUtil.buildSlf4jUtil().loadSlf4j(); } private Logger log = LoggerFactory.getLogger(getClass()); private static String DEFAULT_THUMB_PREVFIX = "thumb_";
private static String DEFAULT_CUT_PREVFIX = "cut_"; private static Boolean DEFAULT_FORCE = false; /** * <p>Title: cutImage</p> * <p>Description: 根據原圖與裁切size擷取區域性圖片</p> * @param srcImg 源圖片 * @param output 圖片輸出流 * @param rect 需要擷取部分的座標和大小 */ public void cutImage(File srcImg, OutputStream output, java.awt.Rectangle rect){ if(srcImg.exists()){ java.io.FileInputStream fis = null; ImageInputStream iis = null; try { fis = new FileInputStream(srcImg); // ImageIO 支援的圖片型別 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif] String types = Arrays.toString(ImageIO.getReaderFormatNames()).replace("]", ","); String suffix = null; // 獲取圖片字尾 if(srcImg.getName().indexOf(".") > -1) { suffix = srcImg.getName().substring(srcImg.getName().lastIndexOf(".") + 1); }// 型別和圖片字尾全部小寫,然後判斷後綴是否合法 if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()+",") < 0){ log.error("Sorry, the image suffix is illegal. the standard image suffix is {}." + types); return ; } // 將FileInputStream 轉換為ImageInputStream iis = ImageIO.createImageInputStream(fis); // 根據圖片型別獲取該種類型的ImageReader ImageReader reader = ImageIO.getImageReadersBySuffix(suffix).next(); reader.setInput(iis,true); ImageReadParam param = reader.getDefaultReadParam(); param.setSourceRegion(rect); BufferedImage bi = reader.read(0, param); ImageIO.write(bi, suffix, output); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(fis != null) fis.close(); if(iis != null) iis.close(); } catch (IOException e) { e.printStackTrace(); } } }else { log.warn("the src image is not exist."); } } public void cutImage(File srcImg, OutputStream output, int x, int y, int width, int height){ cutImage(srcImg, output, new java.awt.Rectangle(x, y, width, height)); } public void cutImage(File srcImg, String destImgPath, java.awt.Rectangle rect){ File destImg = new File(destImgPath); if(destImg.exists()){ String p = destImg.getPath(); try { if(!destImg.isDirectory()) p = destImg.getParent(); if(!p.endsWith(File.separator)) p = p + File.separator; cutImage(srcImg, new java.io.FileOutputStream(p + DEFAULT_CUT_PREVFIX + "_" + new java.util.Date().getTime() + "_" + srcImg.getName()), rect); } catch (FileNotFoundException e) { log.warn("the dest image is not exist."); } }else log.warn("the dest image folder is not exist."); } public void cutImage(File srcImg, String destImg, int x, int y, int width, int height){ cutImage(srcImg, destImg, new java.awt.Rectangle(x, y, width, height)); } public void cutImage(String srcImg, String destImg, int x, int y, int width, int height){ cutImage(new File(srcImg), destImg, new java.awt.Rectangle(x, y, width, height)); } /** * <p>Title: thumbnailImage</p> * <p>Description: 根據圖片路徑生成縮圖 </p> * @param imagePath 原圖片路徑 * @param w 縮圖寬 * @param h 縮圖高 * @param prevfix 生成縮圖的字首 * @param force 是否強制按照寬高生成縮圖(如果為false,則生成最佳比例縮圖) */ public void thumbnailImage(File srcImg, OutputStream output, int w, int h, String prevfix, boolean force){ if(srcImg.exists()){ try { // ImageIO 支援的圖片型別 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif] String types = Arrays.toString(ImageIO.getReaderFormatNames()).replace("]", ","); String suffix = null; // 獲取圖片字尾 if(srcImg.getName().indexOf(".") > -1) { suffix = srcImg.getName().substring(srcImg.getName().lastIndexOf(".") + 1); }// 型別和圖片字尾全部小寫,然後判斷後綴是否合法 if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()+",") < 0){ log.error("Sorry, the image suffix is illegal. the standard image suffix is {}." + types); return ; } log.debug("target image's size, width:{}, height:{}.",w,h); Image img = ImageIO.read(srcImg); // 根據原圖與要求的縮圖比例,找到最合適的縮圖比例 if(!force){ int width = img.getWidth(null); int height = img.getHeight(null); if((width*1.0)/w < (height*1.0)/h){ if(width > w){ h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w/(width*1.0))); log.debug("change image's height, width:{}, height:{}.",w,h); } } else { if(height > h){ w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h/(height*1.0))); log.debug("change image's width, width:{}, height:{}.",w,h); } } } BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics g = bi.getGraphics(); g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null); g.dispose(); // 將圖片儲存在原目錄並加上字首 ImageIO.write(bi, suffix, output); output.close(); } catch (IOException e) { log.error("generate thumbnail image failed.",e); } }else{ log.warn("the src image is not exist."); } } public void thumbnailImage(File srcImg, int w, int h, String prevfix, boolean force){ String p = srcImg.getAbsolutePath(); try { if(!srcImg.isDirectory()) p = srcImg.getParent(); if(!p.endsWith(File.separator)) p = p + File.separator; thumbnailImage(srcImg, new java.io.FileOutputStream(p + prevfix +srcImg.getName()), w, h, prevfix, force); } catch (FileNotFoundException e) { log.error("the dest image is not exist.",e); } } public void thumbnailImage(String imagePath, int w, int h, String prevfix, boolean force){ File srcImg = new File(imagePath); thumbnailImage(srcImg, w, h, prevfix, force); } public void thumbnailImage(String imagePath, int w, int h, boolean force){ thumbnailImage(imagePath, w, h, DEFAULT_THUMB_PREVFIX, DEFAULT_FORCE); } public void thumbnailImage(String imagePath, int w, int h){ thumbnailImage(imagePath, w, h, DEFAULT_FORCE); } public static void main(String[] args) { new ImageUtil().thumbnailImage("imgs/Tulips.jpg", 150, 100); new ImageUtil().cutImage("imgs/Tulips.jpg","imgs", 250, 70, 300, 400); } }
複製程式碼

相關推薦

JAVA生成圖片、JAVA擷取圖片區域性內容

目前,google已經有了更好的處理JAVA圖片的工具,請搜尋:Thumbnailator    package com.ares.image.test; import java.awt.Color; import java.awt.Graphics; impor

JAVA生成圖片、JAVA擷取圖片區域性內容的案例

JAVA生成圖片縮圖 package com.ares.image.test; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.image.Bu

PHP 生成圖片函式

各位小盆友使用前記得開啟 GD 庫的支援哦,附上程式碼。 <?php /** * 生成縮圖函式(支援圖片格式:gif、jpeg、png和bmp) * @author ruxing.li * @param string $src 源圖片路徑 * @p

php實現等比例生成圖片不失真

//等比例生成圖片縮圖不失真 function resizeImage($im,$maxwidth,$maxheight,$name,$filetype){     $pic_width = imagesx($im);     $pic_height = imagesy($

生成圖片

package com.ares.image.test; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io

java生成圖片

當圖片很大的時候,要生成預覽圖來提高網站響應速率,採用java的image相關類來生成縮圖 package com.liuc.core; import java.awt.Image; import java.awt.image.BufferedImage; import

Spring MVC上傳圖片,Java二進位制圖片寫入資料庫,生成

步驟:1.將圖片上傳到伺服器的一個磁碟目錄下。 2.將剛才上傳好的圖片寫入資料庫image欄位。 一、上傳圖片:使用的是spring mvc 對上傳的支援。 jsp 頁面: <form name="uploadForm" id="uploadForm" m

tp5中上傳圖片方法,並生成相應的方法

//接收上傳檔案的name$file = $this->_req->file("upload_head_image");//將上傳的檔案移動到public/uploads/user$info = $file->validate(['size'=>524

nginx使用image_filter生成 -- fasdfs海量圖片整合

1 http_image_filter_module http_image_filter_module是nginx提供的整合圖片處理模組,支援nginx-0.7.54以後的版本,在網站訪問量不是很高磁

使用PHP實現生成固定大小圖片功能(智慧裁剪,圖片不失真)

<?php //影象處理類 class Image { private $file; //圖片地址 private $width; //圖片長度 private $height; //圖片長度 private $type; //圖片型別

Windows Server 2008 顯示圖片

在 Windows Server 2008 中,圖片不能顯示縮圖。 解決辦法: 1. 開啟資源管理器,依次選擇 Organize -> Folder and search options 2. 點選 View 選項卡,將 Always show icons, never thumb

Java——使用javacv生成視訊

轉載大佬文章,以備後期再次需要,親測使用有效 新增依賴 在pom.xml中新增依賴配置 <dependencies>   <dependency>     <groupId>org.bytedeco</groupId

Nginx-Lua-FastDFS-GraphicsMagick動態圖片

Nginx-Lua-FastDFS-GraphicsMagick動態圖片縮圖 公司使用FastDFS來當作圖片伺服器,客戶端通過Nginx請求圖片。某些情況下,客戶端對請求的圖片有尺寸要求, 如 http://10.100.1.145/group1/M00/00/1

Winform下使用ListView控制元件和ImageList控制元件顯示圖片

一、基本概念 1、ImageList控制元件 ImageList元件,又稱為圖片儲存元件,它主要用於儲存圖片資源,然後在控制元件上顯示出來,這樣就簡化了對圖片的管理。ImageList元件的主要屬性是Images,它包含關聯控制元件將要使用的圖片。每個單獨的圖片可以通過其索引值或鍵值來訪問。

Windows7無法顯示.png、.jpg圖片的問題

實驗環境(藍色粗體字為特別注意內容) 1,環境:Windows 7 Ultimate 2,參考文獻http://www.xiazaizhijia.com/rjjc/20481.html 今天開啟電腦的時候突然發現電腦的.png檔案和.jpg檔案的圖示都無法正常顯示,其他格式的縮圖比如wo

CKfinder上傳圖片問題

CKfinder上傳圖片縮圖問題     專案裡CKFinder要求上傳的圖片大小不縮略。 把配置檔案的這個屬性擴大就可以。 附帶ckfinde

Qt QListWidget實現圖片列表

目標: 將本機中的多張圖片以縮圖的形式顯示在列表中 環境: 我們已經做好了選單欄和檔案選擇對話方塊。參考:http://blog.csdn.net/v_xchen_v/article/details/71524160 實現: 以縮圖列表展示圖片的功能寫在mymenu類的成員函式s

php實現按指定大小等比放生成上傳圖片的方法

/** * * *等比縮放 * @param unknown_type srcImage源圖片路徑∗@paramunknowntypetoFile 目標圖片路徑 * @param unknown_type maxWidth最大寬∗

使用MediaStore.Images和 Cursor查詢本地圖片圖片

先看一個例項: String[] projection = { MediaStore.Images.Thumbnails._ID,MediaStore.Images.Thumbnails.DATA}; Cursor cursor = mActivity.getContent

讀取24位 BMP 影象並生成 JPG (一)

            //對24位BMP進行解析     if(nbitcount==24){         int npad=(nsizeimage/nheight)-nwidth*3;         int ndata[]=new int[nheight*nwidth];         byte