服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java input 调用手机相机和本地照片上传图片到服务器然后压缩的方法

java input 调用手机相机和本地照片上传图片到服务器然后压缩的方法

2021-05-26 13:08*眉间缘* Java教程

今天小编就为大家分享一篇java input 实现调用手机相机和本地照片上传图片到服务器然后压缩的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

在微信公众号里面需要上传头像,时间比较紧,调用学习jssdk并使用 来不及 就用了input

1、使用input:file标签, 去调用系统默认相机,摄像,录音功能,其实是有个capture属性,直接说明需要调用什么功能

java" id="highlighter_323750">
?
1
2
3
4
5
<input type="file" accept="image/*" capture="camera">
 
<input type="file" accept="video/*" capture="camcorder">
 
<input type="file" accept="audio/*" capture="microphone">

capture表示,可以捕获到系统默认的设备,比如:camera--照相机;camcorder--摄像机;microphone--录音。

accept表示,直接打开系统文件目录。

2、input:file标签还支持一个multiple属性,表示可以支持多选,如:

?
1
<input type="file" accept="image/*" multiple>

加上这个multiple后,capture就没啥用了,因为multiple是专门用来支持多选的。

用form表单提交

?
1
2
3
4
5
6
7
8
9
10
<form id="uploadform" class="mui-input-group" style="width: 80%;margin: 0 auto;margin-top: 70px" action="/jxs/uploadtou.do" method="post" enctype="multipart/form-data" >
  <div class="mui-input-row">
   <label>图片</label>
   <input required="required" class="mui-input-clear mui-input" type="file" name="file" id="photo_pick" accept="image/*">
  </div>
 
  <div class="mui-content-padded" style="width: 90%;margin: 0 auto;margin-top: 5px;padding: 10px">
   <input style="color:#ffffff ;width: 100%;background: #00f7de" value="上传" type="submit">
  </div>
 </form>

上传之后图片显示在页面上

?
1
<div class="progress_dialog" style="margin-left:30px;margin-top:20px;width: 50%;height: 50%;"></div>

js

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<script>
 /*图片地址
 https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%e9%ab%98%e6%b8%85%e7%be%8e%e5%a5%b3%20%e4%b8%9d%e8%a2%9c%e5%b7%a8%e4%b9%b3&step_word=&hs=0&pn=1&spn=0&di=57234189540&pi=0&rn=1&tn=baiduimagedetail&is=0%2c0&istype=2&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=-1&cs=3589338782%2c536437810&os=3988412231%2c488396405&simid=3515890414%2c233897128&adpicid=0&lpn=0&ln=1389&fr=&fmq=1490709487003_r&fm=result&ic=0&s=undefined&se=&sme=&tab=0&width=&height=&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=&objurl=http%3a%2f%2fwww.bz55.com%2fuploads%2fallimg%2f150416%2f139-1504161ak9.jpg&fromurl=ippr_z2c%24qazdh3fazdh3fooo_z%26e3bkzcc_z%26e3bv54azdh3f4jtgektzitazdh3f8l9c9_z%26e3bip4s&gsm=0&rpstart=0&rpnum=0
 */
 $(function() {
  $("#photo_pick").on("change", function () {
   var file = this.files[0];
   photocompress(file, 50, $(".progress_dialog")[0])
   $(".progress_dialog").show();
   if (!this.files.length) return;
   var files = array.prototype.slice.call(this.files);
   if (files.length > 9) {
    alert("最多同时只可上传9张图片");
    return;
   }
  /* files.foreach(function (file, i) {
    /!*var reader = new filereader();
    reader.onload = function () {
     var imgo = document.createelement("img");
     imgo.src = reader.result;
    }*!/
    reader.readasdataurl(file);
    $(".progress_dialog").hide();*/
   });
  })
 
 
  /*
 三个参数
 file:一个是文件(类型是图片格式),
 w:一个是文件压缩的后宽度,宽度越小,字节越小
 objdiv:一个是容器或者回调函数
 photocompress()
  */
  function photocompress(file, w, objdiv) {
   var ready = new filereader();
   /*开始读取指定的blob对象或file对象中的内容. 当读取操作完成时,readystate属性的值会成为done,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: url格式的字符串以表示所读取文件的内容.*/
   ready.readasdataurl(file);
   ready.onload = function () {
    var re = this.result;
    canvasdataurl(re, w, objdiv)
 
   }
  }
 
  function canvasdataurl(re, w, objdiv) {
   var newimg = new image();
   newimg.src = re;
   var imgwidth, imgheight, offsetx = 0, offsety = 0;
   newimg.onload = function () {
    var img = document.createelement("img");
    img.src = newimg.src;
    imgwidth = img.width;
    imgheight = img.height;
    var canvas = document.createelement("canvas");
    canvas.width = w;
    canvas.height = w;
    var ctx = canvas.getcontext("2d");
    ctx.clearrect(0, 0, w, w);
    if (imgwidth > imgheight) {
     imgwidth = w * imgwidth / imgheight;
     imgheight = w;
     offsetx = -math.round((imgwidth - w) / 6);
    } else {
     imgheight = w * imgheight / imgwidth;
     imgwidth = w;
     offsety = -math.round((imgheight - w) / 6);
    }
    ctx.drawimage(img, offsetx, offsety, imgwidth, imgheight);
    var base64 = canvas.todataurl("image/jpeg", 0.1);
    if (typeof objdiv == "object") {
     objdiv.appendchild(canvas);
    } else if (typeof objdiv == "function") {
     objdiv(base64);
    }
   }
 
 }
</script>

后台接收以及压缩

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
@postmapping("/uploadtou.do")
 public string uploadtou(@requestparam(value = "file") multipartfile file, httpservletrequest request) throws ioexception {
  system.out.println(file);
  string result = "";
  if (!file.isempty()) {
   try {
    shopuser u = (shopuser) request.getsession().getattribute("currentuser");
    string extname = file.getoriginalfilename();
    string filename = file.getname();
    string suffix = extname.substring(extname.lastindexof(".") + 1);
    system.err.println(suffix);
    date now = new date();
    simpledateformat outformat = new simpledateformat("yyyymmddhhmmss");
    string s = outformat.format(now);
    bufferedoutputstream bos = new bufferedoutputstream(
      new fileoutputstream(new file("d:\\xiangmu\\demo\\" + s + "." + suffix)));
    bos.write(file.getbytes());
    bos.flush();
    bos.close();
    /**
     * compress 图片缩放类的使用(缩略图)
     * srcimage 为inputstream对象
     * rectangle 为需要截图的长方形坐标
     * proportion 为压缩比例
     * **/
    inputstream in = null;
    //缩放后需要保存的路径
    file savefile = new file("d:\\xiangmu\\demo\\" + s + s + "." + suffix);
    try {
     //原图片的路径
     in = new fileinputstream(new file("d:\\xiangmu\\demo\\" + s + "." + suffix));
     int length = in.available();
     if (length / 1024 >= 10 && length / 1024 < 100) {
      if (compress(in, savefile, 10)) {
       system.out.println("图片压缩十倍!");
      }
     } else if (length / 1024 >= 100 && length / 1024 < 1000) {
      if (compress(in, savefile, 100)) {
       system.out.println("图片压缩100倍!");
      }
     } else if (length / 1024 >= 1000 && length / 1024 < 10000) {
      if (compress(in, savefile, 1000)) {
       system.out.println("图片压缩1000倍!");
      }
     } else if (length / 1024 < 10 && length / 1024 > 0) {
      if (compress(in, savefile, 1)) {
       system.out.println("图片压缩1倍!");
      }
     }
 
    } catch (exception e) {
     e.printstacktrace();
    } finally {
     in.close();
    }
    string filename = "/path/" + s + s + "." + suffix;//服务器地址
    system.out.println(filename);
    int a = shopservice.updateimg(u.getid(), filename);
    system.out.println(filename);
   } catch (exception e) {
    e.printstacktrace();
   }
  } else {
  }
 
  return "wode.html";
 }

图片处理类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package com.example.springbootshop.util;
 
import org.junit.test;
 
import java.awt.graphics2d;
import java.awt.rectangle;
import java.awt.renderinghints;
import java.awt.geom.affinetransform;
import java.awt.image.bufferedimage;
import java.awt.image.colormodel;
import java.awt.image.writableraster;
import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.ioexception;
import java.io.inputstream;
 
import javax.imageio.imageio;
 
 
 
 
 
/**
 * 图片工具类,完成图片的截取
 * 所有方法返回值均未boolean型
 */
public class imagehelper {
 /**
  * 实现图像的等比缩放
  * @param source
  * @param targetw
  * @param targeth
  * @return
  */
 private static bufferedimage resize(bufferedimage source, int targetw,
          int targeth) {
  // targetw,targeth分别表示目标长和宽
  int type = source.gettype();
  bufferedimage target = null;
  double sx = (double) targetw / source.getwidth();
  double sy = (double) targeth / source.getheight();
  // 这里想实现在targetw,targeth范围内实现等比缩放。如果不需要等比缩放
  // 则将下面的if else语句注释即可
  if (sx < sy) {
   sx = sy;
   targetw = (int) (sx * source.getwidth());
  } else {
   sy = sx;
   targeth = (int) (sy * source.getheight());
  }
  if (type == bufferedimage.type_custom) { // handmade
   colormodel cm = source.getcolormodel();
   writableraster raster = cm.createcompatiblewritableraster(targetw,
     targeth);
   boolean alphapremultiplied = cm.isalphapremultiplied();
   target = new bufferedimage(cm, raster, alphapremultiplied, null);
  } else
   target = new bufferedimage(targetw, targeth, type);
  graphics2d g = target.creategraphics();
  // smoother than exlax:
  g.setrenderinghint(renderinghints.key_interpolation,
    renderinghints.value_interpolation_bicubic);
  g.drawrenderedimage(source, affinetransform.getscaleinstance(sx, sy));
  g.dispose();
  return target;
 }
 
 /**
  * 实现图像的等比缩放和缩放后的截取, 处理成功返回true, 否则返回false
  * @param infilepath 要截取文件的路径
  * @param outfilepath 截取后输出的路径
  * @param width 要截取宽度
  * @param hight 要截取的高度
  * @throws exception
  */
 public static boolean compress(string infilepath, string outfilepath,
         int width, int hight) {
  boolean ret = false;
  file file = new file(infilepath);
  file savefile = new file(outfilepath);
  inputstream in = null;
  try {
   in = new fileinputstream(file);
   ret = compress(in, savefile, width, hight);
  } catch (filenotfoundexception e) {
   e.printstacktrace();
   ret = false;
  } finally{
   if(null != in){
    try {
     in.close();
    } catch (ioexception e) {
     e.printstacktrace();
    }
   }
  }
 
  return ret;
 }
 
 /**
  * 实现图像的等比缩放和缩放后的截取, 处理成功返回true, 否则返回false
  * @param in 要截取文件流
  * @param outfilepath 截取后输出的路径
  * @param width 要截取宽度
  * @param hight 要截取的高度
  * @throws exception
  */
 public static boolean compress(inputstream in, file savefile,
         int width, int hight) {
//  boolean ret = false;
  bufferedimage srcimage = null;
  try {
   srcimage = imageio.read(in);
  } catch (ioexception e) {
   e.printstacktrace();
   return false;
  }
 
  if (width > 0 || hight > 0) {
   // 原图的大小
   int sw = srcimage.getwidth();
   int sh = srcimage.getheight();
   // 如果原图像的大小小于要缩放的图像大小,直接将要缩放的图像复制过去
   if (sw > width && sh > hight) {
    srcimage = resize(srcimage, width, hight);
   } else {
    string filename = savefile.getname();
    string formatname = filename.substring(filename
      .lastindexof('.') + 1);
    try {
     imageio.write(srcimage, formatname, savefile);
    } catch (ioexception e) {
     e.printstacktrace();
     return false;
    }
    return true;
   }
  }
  // 缩放后的图像的宽和高
  int w = srcimage.getwidth();
  int h = srcimage.getheight();
  // 如果缩放后的图像和要求的图像宽度一样,就对缩放的图像的高度进行截取
  if (w == width) {
   // 计算x轴坐标
   int x = 0;
   int y = h / 2 - hight / 2;
   try {
    savesubimage(srcimage, new rectangle(x, y, width, hight), savefile);
   } catch (ioexception e) {
    e.printstacktrace();
    return false;
   }
  }
  // 否则如果是缩放后的图像的高度和要求的图像高度一样,就对缩放后的图像的宽度进行截取
  else if (h == hight) {
   // 计算x轴坐标
   int x = w / 2 - width / 2;
   int y = 0;
   try {
    savesubimage(srcimage, new rectangle(x, y, width, hight), savefile);
   } catch (ioexception e) {
    e.printstacktrace();
    return false;
   }
  }
 
  return true;
 }
 
 /**
  * 实现图像的等比缩放和缩放后的截取, 处理成功返回true, 否则返回false
  * @param in 图片输入流
  * @param savefile 压缩后的图片输出流
  * @param proportion 压缩比
  * @throws exception
  */
 public static boolean compress(inputstream in, file savefile, int proportion) {
  if(null == in
    ||null == savefile
    ||proportion < 1){// 检查参数有效性
   //loggerutil.error(imagehelper.class, "--invalid parameter, do nothing!");
   return false;
  }
 
  bufferedimage srcimage = null;
  try {
   srcimage = imageio.read(in);
  } catch (ioexception e) {
   e.printstacktrace();
   return false;
  }
  // 原图的大小
  int width = srcimage.getwidth() / proportion;
  int hight = srcimage.getheight() / proportion;
 
  srcimage = resize(srcimage, width, hight);
 
  // 缩放后的图像的宽和高
  int w = srcimage.getwidth();
  int h = srcimage.getheight();
  // 如果缩放后的图像和要求的图像宽度一样,就对缩放的图像的高度进行截取
  if (w == width) {
   // 计算x轴坐标
   int x = 0;
   int y = h / 2 - hight / 2;
   try {
    savesubimage(srcimage, new rectangle(x, y, width, hight), savefile);
   } catch (ioexception e) {
    e.printstacktrace();
    return false;
   }
  }
  // 否则如果是缩放后的图像的高度和要求的图像高度一样,就对缩放后的图像的宽度进行截取
  else if (h == hight) {
   // 计算x轴坐标
   int x = w / 2 - width / 2;
   int y = 0;
   try {
    savesubimage(srcimage, new rectangle(x, y, width, hight), savefile);
   } catch (ioexception e) {
    e.printstacktrace();
    return false;
   }
  }
 
  return true;
 }
 
 /**
  * 实现缩放后的截图
  * @param image 缩放后的图像
  * @param subimagebounds 要截取的子图的范围
  * @param subimagefile 要保存的文件
  * @throws ioexception
  */
 private static void savesubimage(bufferedimage image,
          rectangle subimagebounds, file subimagefile) throws ioexception {
  if (subimagebounds.x < 0 || subimagebounds.y < 0
    || subimagebounds.width - subimagebounds.x > image.getwidth()
    || subimagebounds.height - subimagebounds.y > image.getheight()) {
   //loggerutil.error(imagehelper.class, "bad subimage bounds");
   return;
  }
  bufferedimage subimage = image.getsubimage(subimagebounds.x,subimagebounds.y, subimagebounds.width, subimagebounds.height);
  string filename = subimagefile.getname();
  string formatname = filename.substring(filename.lastindexof('.') + 1);
  imageio.write(subimage, formatname, subimagefile);
 }
 
 
 @test
 public static void main(string[] args) throws exception {
 
  /**
   * savesubimage 截图类的使用
   * srcimage 为bufferedimage对象
   * rectangle 为需要截图的长方形坐标
   * savefile 需要保存的路径及名称
   * **/
  //需要截图的长方形坐标
  /*rectangle rect =new rectangle();
  rect.x=40;
  rect.y=40;
  rect.height=160;
  rect.width=160;
 
  inputstream in = null;
  //需要保存的路径及名称
  file savefile = new file("d:\\ioc\\files\\aaa2.jpg");
  //需要进行处理的图片的路径
  in = new fileinputstream(new file("d:\\ioc\\files\\aaa.jpg"));
  bufferedimage srcimage = null;
  //将输入的数据转为bufferedimage对象
  srcimage = imageio.read(in);
 
  imagehelper img=new imagehelper();
  img.savesubimage(srcimage, rect, savefile);*/
 
  /**
   * compress 图片缩放类的使用(缩略图)
   * srcimage 为inputstream对象
   * rectangle 为需要截图的长方形坐标
   * proportion 为压缩比例
   * **/
  inputstream in = null;
  //缩放后需要保存的路径
  file savefile = new file("d:\\xiangmu\\demo\\20180523192742img_0049123.jpg");
  try {
   //原图片的路径
   in = new fileinputstream(new file("d:\\xiangmu\\demo\\20180523192742img_0049.jpg"));
   if(compress(in, savefile, 10)){
    system.out.println("图片压缩十倍!");
   }
  } catch (exception e) {
   e.printstacktrace();
  } finally {
   in.close();
  }
 }
}

以上这篇java input 调用手机相机和本地照片上传图片到服务器然后压缩的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/NCL--/p/9103679.html

延伸 · 阅读

精彩推荐