电竞比分网-中国电竞赛事及体育赛事平台

分享

java中怎么將本地圖片上傳到服務(wù)器上

 青_春 2016-03-18
     public String LoadImageToServer(String filePath,String serverPath) throws Exception {

    String resultPath = "";          //上傳后圖片所在的路徑
    FileOutputStream out = null;     //文件輸出流
    try {                               //驗(yàn)證圖片上傳的格式是否正確
     File f = new File(filePath);
        if (!f.isFile()) {
        throw new Exception(f " 不是圖片文件!");
    }
     if (f != null && f.exists()) {          //這里的ImageIO屬于java工廠類,在工廠類class里面,調(diào)用的System.gc(),頻繁調(diào)用會(huì)造成dump,需要考慮優(yōu)化
        BufferedImage image = ImageIO.read(f); // 讀入文件
        if (image != null) {
        BufferedImage tag = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);  //構(gòu)造一個(gè)類型為預(yù)定義圖像類型之一的 BufferedImage
           tag.getGraphics().drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);                     //繪制所需要尺寸大小的圖片
        /*
         * 以下生成圖片上傳后在服務(wù)器上的新路徑
         */
        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;                          //以系統(tǒng)時(shí)間來隨機(jī)的創(chuàng)建圖片文件名
        String fileType = filePath.substring(lastLength);              //獲取上傳圖片的類型
        resultPath = serverPath "site" imageName fileType;
        /*
         * 進(jìn)行圖片的繪制
         */
        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 = null;
      }
     }

     f = null;

    } catch (Exception ex) {
     ex.printStackTrace();
    } finally {
     out.close();
     out = null;
    }
    return resultPath;
   }

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約