若一个项目中图片的资源较多,都会有专门的图片服务器来存储图片,可以去观察一些大的网站上图片的链接都是有专门的服务器,这样可以很好地提高性能。图片服务器解决方案很多,通过花钱的云厂商提供的存储服务、vsftp、FastDFS等,这里介绍一个开源项目——zimg。
- zimg是图像存储和处理服务器。您可以使用URL参数从zimg获得压缩和缩放的图像。
- zimg的并发I / O,分布式存储和及时处理能力非常出色。您不再需要在图像服务器中使用nginx。在基准测试中,zimg可以在高并发级别上每秒处理3000个以上的图像下载任务和每秒90000个以上的HTTP回显请求。性能高于PHP或其他图像处理服务器。
- 用于中小型的图床服务
- 官网地址:http://zimg.buaa.us
1 、安装
# 拉取zimg镜像 $ docker pull iknow0612/zimg # 启动zimg容器 $ docker run -it -d -p 4869:4869 -v /data/zimg/:/zimg/bin/img --name my_zimg iknow0612/zimg sh app.sh
说明:
- 若是在前端浏览器页面直接上传,那么返回结果是html格式
- 若是通过发起post请求则是返回json格式
{“ret”:true,“info”:{“md5”:“5f189d8ec57f5a5a0d3dcba47fa797e2”,“size”:29615}}
2、zimg简单说明
$ docker exec -ti zimg容器id /bin/bash

- conf:配置文件
- img:图片存放目录
- log:日志
- script:脚本文件
- www:两个html页面文件
3. zimg与java
基本的示例,发起post请求,将图片的字节数据写入六中即可。
@Test public void test() throws IOException {
URL url = new URL("http://192.168.175.130:4869/update"); File file = new File("C:\\Users\\lr\\Desktop\\t.png"); String name = file.getName(); String fileType = name.substring(name.lastIndexOf(".") + 1); HttpURLConnection connection = null; InputStream response = null; try {
connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); // 设置上传图片的类型,否则报错 connection.setRequestProperty("content-type", fileType); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.connect(); OutputStream out = connection.getOutputStream(); out.write(getFileBytes(file)); response = connection.getInputStream(); int len = -1; String ret = ""; byte[] b = new byte[100]; while ((len = response.read(b)) != -1) {
ret += new String(b,0,len); } System.out.println(ret); } catch (MalformedURLException e) {
e.printStackTrace(); } catch (IOException e) {
e.printStackTrace(); } finally {
if (response != null) try {
response.close(); } catch (IOException e) {
e.printStackTrace(); } if (connection != null) {
connection.disconnect(); connection = null; } } } private byte[] getFileBytes(File file) {
FileInputStream in = null; ByteArrayOutputStream bos = null; try {
in = new FileInputStream(file); bos = new ByteArrayOutputStream(); int len = -1; byte[] b = new byte[1024]; while((len = in.read(b)) != -1) {
bos.write(b, 0, len); } return bos.toByteArray(); } catch (FileNotFoundException e) {
e.printStackTrace(); } catch (IOException e) {
e.printStackTrace(); }finally {
if(in !=null) {
try {
in.close(); } catch (IOException e) {
e.printStackTrace(); } } if(bos != null) {
try {
bos.close(); } catch (IOException e) {
e.printStackTrace(); } } } return null; }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/214505.html原文链接:https://javaforall.net
