img标签显示图片方法总结
Posted will-666
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了img标签显示图片方法总结相关的知识,希望对你有一定的参考价值。
1、通过图片在项目下的可访问路径。
例如:<img src=‘../assets/imags/xxx.jpg‘ />
2、通过一个下载器链接,读取(文件)服务器上的图片资源。
例如:<img src=‘http://ip:port/projectName/getImageServlet?imagesPath‘ />
后端代码:
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();
3、base64加密数据填充法。
例如:<img src="data:image/gif;base64,R0lGODlhHAAmAKIHAKqqqsvLy0hISObm5vf394uLiwAAAP///yH5B… EoqQqJKAIBaQOVKHAXr3t7txgBjboSvB8EpLoFZywOAo3LFE5lYs/QW9LT1TRk1V7S2xYJADs=">
后端代码:
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;
以上是关于img标签显示图片方法总结的主要内容,如果未能解决你的问题,请参考以下文章