Java圖片上傳

來源:互聯網
上載者:User

標籤:圖片上傳   壓縮大小   

             圖片上傳,其實,也可以按照之前文章——檔案上傳的方式實現,因為圖片也是檔案。只要是檔案,都可以用流來接收,然後把流給寫出到指定的物理空間下,形成我們需要的物理檔案。

             今天,我們就不用上傳檔案的方式,這種方式和我之前的一篇製作二維碼的文章類似。首先,讀檔案,需要知道檔案的路徑,比如放在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圖片上傳

聯繫我們

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