標籤:圖片上傳 壓縮大小
圖片上傳,其實,也可以按照之前文章——檔案上傳的方式實現,因為圖片也是檔案。只要是檔案,都可以用流來接收,然後把流給寫出到指定的物理空間下,形成我們需要的物理檔案。
今天,我們就不用上傳檔案的方式,這種方式和我之前的一篇製作二維碼的文章類似。首先,讀檔案,需要知道檔案的路徑,比如放在C盤下面的某個檔案。然後把這個圖片通過畫筆方式給畫出來。放到指定伺服器路徑下。不需要第三方外掛程式,sun公司提供的image工具類就可以實現。
下面我們把案頭上的blue.png圖片上傳到伺服器上。
public static String imgUpload(HttpServletRequest request, HttpServletResponse response) throws Exception { String resultPath = ""; String filePath = "C:/Users/Administrator/Desktop/blue.png"; String savePath = request.getRealPath("/save/"); File uploadDir = new File(savePath); File file = new File(filePath); if ( !file.isFile()) { return "不是檔案類型"; } if ( !uploadDir.exists()) { uploadDir.mkdirs(); } BufferedImage img = ImageIO.read(file); if (img != null) { BufferedImage tag = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(img, 0, 0, img.getWidth(), img.getHeight(), null); int lastLength = filePath.lastIndexOf("."); Date date = new Date(System.currentTimeMillis()); String strDate = new SimpleDateFormat("yyyyMMddhhmmss").format(date); int random = (int) (Math.random() * 99); String imageName = strDate + random; //以系統時間來隨機的建立圖片檔案名稱 String fileType = filePath.substring(lastLength); //擷取上傳圖片的類型 resultPath = savePath + imageName + fileType; System.out.println(resultPath); FileOutputStream out = new FileOutputStream(resultPath); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(tag); param.setQuality(0.95f, true); //95%映像 param.setDensityUnit(1); //像素尺寸單位.像素/英寸 param.setXDensity(300); //水平解析度 param.setYDensity(300); //垂直解析度 encoder.setJPEGEncodeParam(param); encoder.encode(tag); tag.flush(); out.flush(); out.close(); return resultPath; }
這種方式上傳圖片,好處就在於,可以控製圖片的大小尺寸,可以按照自己的需要進行裁剪壓縮圖片。
Java圖片上傳