欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-22 12:42:34
在微信公众号里面需要上传头像,时间比较紧,调用学习jssdk并使用 来不及 就用了input 1、使用input:file标签, 去调用系统默认相机,摄像,录音功能,其实...

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

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

<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属性,表示可以支持多选,如:

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

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

用form表单提交

<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>

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

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

js

<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>

后台接收以及压缩

@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";
 }

图片处理类

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 调用手机相机和本地照片上传图片到服务器然后压缩的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。