img標籤顯示圖片方法總結

一、經過圖片在項目下的可訪問路徑。後端

  例如:<img src='../assets/imags/xxx.jpg' />服務器

 

二、經過一個下載器連接,讀取(文件)服務器上的圖片資源。加密

  例如:<img src='http://ip:port/projectName/getImageServlet?imagesPath' />spa

  後端代碼:code

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String imagePath = "D://牙牙牙白.gif";
        String contentType = "";
        String lowerPath = imagePath.toLowerCase();
        if(lowerPath.endsWith("jpg") || lowerPath.endsWith("jpe") || lowerPath.endsWith("jpeg")){
            contentType = "image/jpeg;charset=utf-8";
        } else if (lowerPath.endsWith("png")) {
            contentType = "image/png;charset=utf-8";
        } else if (lowerPath.endsWith("bmp")) {
            contentType = "image/bmp;charset=utf-8";
        } else if (lowerPath.endsWith("gif")) {
            contentType = "image/gif;charset=utf-8";
        }
        response.setContentType(contentType);
        
        // 文件流的方式
        InputStream in = new FileInputStream(imagePath);// 輸入流
        OutputStream out = response.getOutputStream();// 輸出流
        
        // 邊讀邊寫
        byte[] bt = new byte[1024];
        int length = 0;
        while ((length = in.read(bt)) != -1) {
            out.write(bt, 0, length);
        }
        // 關閉流
        in.close();
        out.flush();
        out.close();
    }  圖片

 

三、base64加密數據填充法。ip

  例如:<img src="data:image/gif;base64,R0lGODlhHAAmAKIHAKqqqsvLy0hISObm5vf394uLiwAAAP///yH5B…  EoqQqJKAIBaQOVKHAXr3t7txgBjboSvB8EpLoFZywOAo3LFE5lYs/QW9LT1TRk1V7S2xYJADs=">utf-8

  後端代碼:資源

  public static String getImageBase64() throws Exception{
        String imagePath = "D://牙牙牙白.gif";
        String contentType = "";
        String lowerPath = imagePath.toLowerCase();
        if(lowerPath.endsWith("jpg") || lowerPath.endsWith("jpe") || lowerPath.endsWith("jpeg")){
            contentType = "image/jpeg";
        } else if (lowerPath.endsWith("png")) {
            contentType = "image/png";
        } else if (lowerPath.endsWith("bmp")) {
            contentType = "image/bmp";
        } else if (lowerPath.endsWith("gif")) {
            contentType = "image/gif";
        }
        
        InputStream in = new FileInputStream(imagePath);// 輸入流
        ByteArrayOutputStream out = new ByteArrayOutputStream(); // 輸出流
        // 邊讀邊寫
        byte[] buffer = new byte[1024];
        int length = 0;
        while ((length = in.read(buffer)) != -1) {
            out.write(buffer, 0, length);
        }
        // 關閉流
        in.close();
        out.flush();
        out.close();
        
        // import sun.misc.BASE64Encoder
        BASE64Encoder encoder = new BASE64Encoder();
        String imageBase64 = new String(encoder.encode(out.toByteArray()));
        String imageSrc = "data:" + contentType + ";base64," + imageBase64;
        
        return imageSrc;
    }get

相關文章
相關標籤/搜索