項目中圖片處理總結

來源:互聯網
上載者:User
項目中圖片處理總結項目中的圖片處理方案:
1、將圖片儲存到項目中的image檔案夾底下(這是最初的設計,當時考慮這樣頁面擷取圖片比較簡單)
2、將圖片儲存的物理磁碟上,相對於項目路徑(將第一種方案改為第二種方案的原因是考慮到包替換的時候會把原來的圖片替換掉。版本升級和包替換都不方便)
3、將圖片儲存到物理磁碟、固定盤符、固定檔案夾底下(將第二總方案改為第三中方案的原因是考慮到雙機,必須把圖片儲存到共用磁碟上)
4、將圖片儲存到資料庫(沒使用這總方法,原因是這總方法的佔用資料庫的空間,讀取的時候也有效能問題)
5、將圖片儲存到圖片伺服器(可惜本項目沒有圖片伺服器)

下面儲存圖片



//先儲存圖片到伺服器 if (imageBean.getImageFile() != null && imageBean.getImageFile().length() > 0){//得到圖片名稱String imageName = imageBean.getImageFileFileName();File file = imageBean.getImageFile();//擷取圖片尾碼String ext = imageName.substring(imageName.lastIndexOf('.') + 1).toLowerCase(Locale.CHINA);//重建檔案名稱String filename = UUID.randomUUID().toString() + "." + ext;//構建檔案名稱//構建檔案儲存的目錄 這是方案一的實現//String pathdir = "/images/room/prototype";//得到圖片儲存目錄的真實路徑 這是方案二的實現//String realpathdir = new File(suiteImagePath).getCanonicalFile().getPath();//String realpathdir = ServletActionContext.getServletContext().getRealPath(pathdir);//FileTools.saveFile(file, realpathdir, filename);//這個方法是儲存檔案到對應的路徑FileTools.saveFile(file, suiteImagePath, filename);imageBean.setName(filename);imageBean.setPullpath(suiteImagePath + "/" + filename);}//儲存圖片到資料庫int id = imageDAO.addImage(imageBean);imageBean.setId(id);return imageBean;

struts2具體如何上傳檔案這就不多說了、 儲存圖片就這麼解決了。

接下來看下頁面如何擷取圖片



<img src="../showImage.action?imagePath=${imageBean.pullpath}" />

背景處理是


        InputStream file = null;        OutputStream toClient = null;        try        {            //imagePath = new File(imagePath).getCanonicalFile().getPath();            file = new FileInputStream(new File(imagePath));            //int i = file.available(); // 得到檔案大小            byte data[] = new byte[KeyConstant.DEFAULT_BYTE_SIZE];            int endFlag = 0;            ServletActionContext.getResponse().setContentType("image/*"); // 設定返回的檔案類型            toClient = ServletActionContext.getResponse().getOutputStream(); // 得到向用戶端輸出位元據的對象            while (endFlag != -1)            {                endFlag = file.read(data);                if (endFlag == -1)                {                    break;                }                toClient.write(data, 0, endFlag); // 輸出資料            }            toClient.flush();            toClient.close();        }...後面是處理異常和關閉流

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.