標籤:style blog color os io 使用 java ar for
<1> 使用html標籤上傳需要裁剪的大圖。<2> 在頁面呈現大圖,使用Jcrop(Jquery)對大圖進行裁剪,並且可以進行預覽。<3> 選擇好截取部分之後發送資料給Action,在伺服器端使用 Java API 對大圖進行裁剪。<4> 儲存大圖裁剪好的頭像到指定目錄,完成業務。下面一步一步做:第一步:使用html標籤上傳需要裁剪的大圖。這一步說白了也就是使用Struts2內建的FileUpload功能,把圖片進行上傳具體代碼如下:html頁面:[html] view plaincopy<form id="ulform" action="uploadPic.action" enctype="multipart/form-data" method="post"> <input type="file" name="pic" id="file" value="選擇圖片" /> <input type="submit" value="點擊上傳" /> </form> Struts2設定檔[html] view plaincopy<action name="uploadPic" class="com.luoxiao.tbms.user.action.UserAction" method="uploadPic"> <result name="success" type="redirect">changePic.jsp</result> <result name="error">changePic.jsp</result> </action> 根據配置點擊提交按鈕,會提交表單,把圖片以流的形式發送給 UserAction的uploadPic方法,該方法如下:[java] view plaincopypublic class UserAction{ private File pic; //(在此省略 get 和 set 方法) private String picFileName; //(省略get和set方法, 該屬性Struts2會自動賦值為上傳檔案的檔案名稱) public String uploadPic() { String[] str = { ".jpg", ".jpeg", ".bmp", ".gif" }; // 擷取使用者登入名稱 TbUser curruser = (TbUser) getValue(SCOPE_SESSION, "curruser"); // 限定檔案大小是4MB if (pic == null || pic.length() > 4194304) { //檔案過大 return "error"; } for (String s : str) { if (picFileName.endsWith(s)) { String realPath = ServletActionContext.getServletContext().getRealPath("/uploadpic");// 在tomcat中儲存圖片的實際路徑 == "webRoot/uploadpic/" File saveFile = new File(new File(realPath), "新檔案名稱.jpg"); // 在該實際路徑下執行個體化一個檔案 // 判斷父目錄是否存在 if (!saveFile.getParentFile().exists()) { saveFile.getParentFile().mkdirs(); } try { // 執行檔案上傳 // FileUtils 類名 org.apache.commons.io.FileUtils; // 是commons-io包中的,commons-fileupload 必須依賴 // commons-io包實現檔案上次,實際上就是將一個檔案轉換成流檔案進行讀寫 FileUtils.copyFile(pic, saveFile); } catch (IOException e) { return "imageError"; } } } return "success"; } } 這樣就可以把使用者選擇的圖片上傳到tomcat的webRoot/uploadpic/檔案夾下。 然後訪問頁面,頁面中就可以顯示出剛剛上傳的大圖了。代碼如下。[html] view plaincopy<div style="width: 500px; height: 500px;"> <img style="margin-top:20px;" src="../uploadpic/上傳檔案名稱.jpg"/>" id="target" /> </div> 第一步完成。第二步:使用Jcrop外掛程式裁剪該圖片,並且在頁面中預覽。Jcrop是一個基於JQuery的成熟的圖片裁剪的外掛程式。想要使用它,需要去官方網站下載該js,現給出一個地址:(附帶jquery)點擊去往Jcrop外掛程式下載頁面該外掛程式使用比較簡單:<1> 在裁剪圖片頁面中,引入兩個js檔案,和1個Jcrop需要的css檔案(Jcrop包中有,注意引入順序,先引入jquery):[html] view plaincopy<script src="../js/jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../js/jquery.Jcrop.js" type="text/javascript"></script> <link rel="stylesheet" href="../css/jquery.Jcrop.css" type="text/css" /> <2> 在html頁面中按照Jcrop要求的格式編寫兩個img標籤,一個用作裁剪後的預覽,一個用作顯示大圖,代碼如下:[html] view plaincopy預覽: <div style="width:200px;height:200px;overflow:hidden; border:1px solid gray;"> <img id="preview" width="200px" height="200px" /> </div> 原圖: <img src="../uploadpic/上傳大圖.jpg" id="target" /> <3> 在該頁面中寫js代碼,使其可以裁剪圖片並且預覽:[javascript] view plaincopy<script type="text/javascript"> var x; var y; var width; var height; $(function(){ var jcrop_api, boundx, boundy; <span style="color:#ff0000;">//使原圖具有裁剪功能</span> $(‘#target‘).Jcrop({ onChange: updatePreview, onSelect: updatePreview, aspectRatio: 1 },function(){ // Use the API to get the real image size var bounds = this.getBounds(); boundx = bounds[0]; boundy = bounds[1]; // Store the API in the jcrop_api variable jcrop_api = this; }); <span style="color:#ff0000;">//裁剪過程中,每改變裁剪大小執行該函數</span> function updatePreview(c){ if (parseInt(c.w) > 0){ $(‘#preview‘).css({ width: Math.round(<span style="color:#ff0000;">200 </span>/ c.w * boundx) + ‘px‘, <span style="color:#ff0000;">//200 為預覽div的寬和高</span> height: Math.round(<span style="color:#ff0000;">200 </span>/ c.h * boundy) + ‘px‘, marginLeft: ‘-‘ + Math.round(200 / c.w * c.x) + ‘px‘, marginTop: ‘-‘ + Math.round(200 / c.h * c.y) + ‘px‘ }); <span style="color:#ff0000;">$(‘#width‘).val(c.w); //c.w 裁剪地區的寬 $(‘#height‘).val(c.h); //c.h 裁剪地區的高 $(‘#x‘).val(c.x); //c.x 裁剪地區左上方頂點相對於圖片左上方頂點的x座標 $(‘#y‘).val(c.y); //c.y 裁剪地區頂點的y座標</span> } }; }); </script> 至此我們已經可以看到裁剪之後的樣子了,並且也可以得到裁剪地區的x,y,height,width屬性。第三步:把截取的該地區的屬性傳遞給action,讓action根據所得屬性,利用javaAPI把原圖裁剪成小圖。<1> 設定form表單與隱藏欄位表單組件,並且在裁剪的時候對該四個組件的value屬性賦值[html] view plaincopy<form action="cutPic.action" method="post"> 點擊 <input type="hidden" name="image.x" id="x"/> <input type="hidden" name="image.y" id="y"/> <input type="hidden" name="image.width" id="width"/> <input type="hidden" name="image.height" id="height"/> <input type="submit" value="確定" /> ,設定完成。 </form> <2> 點擊確定,提交該表單,訪問action,配置如下:[html] view plaincopy<action name="cutPic" class="com.luoxiao.tbms.user.action.UserAction" method="cutPic"> <result name="success" type="redirectAction">../announcement/announcement_list.action</result> </action> <3>Struts2帶著四個參數訪問UserAction,並且會自動給UserAction中的image屬性賦值,該image屬性為OperateImage的一個執行個體對象,該類為裁剪圖片類,代碼如下:[java] view plaincopypackage com.luoxiao.util; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; public class OperateImage { // ===源圖片路徑名稱如:c:\1.jpg private String srcpath; // ===剪下圖片存放路徑名稱.如:c:\2.jpg private String subpath; // ===剪下點x座標 private int x; private int y; // ===剪下點寬度 private int width; private int height; <span style="color:#ff0000;">(省略四個屬性的get & set)</span> public OperateImage() { } /** 對圖片裁剪,並把裁剪完的新圖片儲存 */ public void cut() throws IOException { FileInputStream is = null; ImageInputStream iis = null; try { // 讀取圖片檔案 is = new FileInputStream(srcpath); /* * 返回包含所有當前登入 ImageReader 的 Iterator,這些 ImageReader 聲稱能夠解碼指定格式。 * 參數:formatName - 包含非正式格式名稱 . (例如 "jpeg" 或 "tiff")等 。 */ Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpg"); ImageReader reader = it.next(); // 擷取圖片流 iis = ImageIO.createImageInputStream(is); /* * <p>iis:讀取源.true:只向前搜尋 </p>.將它標記為 ‘只向前搜尋’。 * 此設定意味著包含在輸入源中的映像將只按順序讀取,可能允許 reader 避免緩衝包含與以前已經讀取的映像關聯的資料的那些輸入部分。 */ reader.setInput(iis, true); /* * <p>描述如何對流進行解碼的類<p>.用於指定如何在輸入時從 Java Image I/O * 架構的上下文中的流轉換一幅映像或一組映像。用於特定映像格式的外掛程式 將從其 ImageReader 實現的 * getDefaultReadParam 方法中返回 ImageReadParam 的執行個體。 */ ImageReadParam param = reader.getDefaultReadParam(); /* * 圖片裁剪地區。Rectangle 指定了座標空間中的一個地區,通過 Rectangle 對象 * 的左上頂點的座標(x,y)、寬度和高度可以定義這個地區。 */ Rectangle rect = new Rectangle(x, y, width, height); // 提供一個 BufferedImage,將其用作解碼像素資料的目標。 param.setSourceRegion(rect); /* * 使用所提供的 ImageReadParam 讀取通過索引 imageIndex 指定的對象,並將 它作為一個完整的 * BufferedImage 返回。 */ BufferedImage bi = reader.read(0, param); // 儲存新圖片 ImageIO.write(bi, "jpg", new File(subpath)); } finally { if (is != null) is.close(); if (iis != null) iis.close(); } } } <4> 給該類的執行個體的四個屬性 x,y,width,height賦值之後,訪問action中的cutPic方法,代碼如下:[java] view plaincopypublic class UserAction extends BaseAction { private OperateImage image;(省略get set) private File pic; // 接收這個上傳的檔案 private String picFileName; // Struts2提供的格式,在檔案名稱後+FileName就是上傳檔案的名字 /** * 裁剪頭像 */ public String cutPic(){ <span style="color:#ff0000;"> String name = ServletActionContext.getServletContext().getRealPath("/uploadpic/原圖名.jpg"); image.setSrcpath(name); image.setSubpath(ServletActionContext.getServletContext().getRealPath("/uploadpic/裁剪靶心圖表名.jpg")); try { image.cut(); //執行裁剪操作 執行完後即可產生靶心圖表在對應檔案夾內。</span> } catch (IOException e) { e.printStackTrace(); } return "success"; } } 第四步:把截取好的頭像儲存在具體檔案夾下即可,裁剪過程完成。
struts2+jsp+jquery+Jcrop實現圖片裁剪並上傳