angularjs上传图片并转换成base64保存到数据库

1、前台:

jsp

<div style="width: 160px;height: 130px;border-radius: 16px;position: relative;">
    <a href="javascript:;"
       style="position: absolute;width: 100%;height: 100%;">
        <div style="width: 100%;height: 100%;">
            <img ng-if="loginedAccount.photo" id="photo" width="100%" height="100%" ng-src="{{data.photodata}}">
            <img ng-if="!loginedAccount.photo" id="photo" width="100%" height="100%" src="images/g1.jpg">
        </div>
        <input id="file" file-model="data.photo_file" type="file" style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index: 4;opacity: 0;">
    </a>
</div>
js
<pre name="code" class="javascript">var limitSize = 1 * 1024 * 1024;
  $scope.$watch("data.photo_file", function (newValue, oldValue) {
    if ($scope.data && $scope.data.photo_file) {
      if (!oldValue || newValue.size != oldValue.size) {
        if (newValue.size <= limitSize) {
          var file = document.getElementById("file").files[0];
          $("#photo").attr("src", window.URL.createObjectURL(file));
        } else {
          alert("图片大小不得超过1M!");
        }
      }
    }
  });


记得引js包。
 
<script src="bower_components/angular-file-upload/dist/angular-file-upload.min.js"></script>

2、springmvc-servlet.xml配置文件配置:
	<!-- 处理文件上传 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!--1024*2000即2M-->
		<property name="maxUploadSize" value="2048000"/>
		<!--resolveLazily属性启用是为了推迟文件解析,以便在UploadAction 中捕获文件大小异常-->
		<property name="resolveLazily" value="true"/>

		<property name="uploadTempDir" value="/WEB-INF/upload"/>
		<!-- 上传后的目录名 (WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE) -->
		<property name="maxInMemorySize" value="2048000"/>
		<property name="defaultEncoding" value="UTF-8"/>
	</bean>
3、在build.gradle配置文件中添加上传所需要的包。
compile group: 'commons-fileupload', name: 'commons-fileupload', version:'1.3.1'
    compile group: 'commons-io', name: 'commons-io', version:'2.4'
4、后台
public ViewData getXXX(@RequestParam MultipartFile[] photo_file, String xx, String xx, String xx, String xx, String xx,
                               HttpServletRequest request) {
        ViewData vd = new ViewData();
        String base64photo = "";
        if (photo_file != null && photo_file.length > 0) {
//            System.out.println("文件大小:" + photo_file[0].getSize());
            MultipartFile file = photo_file[0];
            if (file.getSize() < 1 * 1024 * 1024) {
                //获取图片的字节流
                byte[] bytePhoto = FileUtils.file2Byte(photo_file[0]);
                //压缩图片
                base64photo = FileUtils.resize(bytePhoto, 300, 0.7f);
//                System.out.println("字符长度:" + base64photo.length());
            } else {
                return vd.error("照片大小不能超过1M!");
            }
        }
        ....
    }
FileUtils
/** 文件转字节
     * @param file
     * @return
     */
    public static byte[] file2Byte(MultipartFile file) {
        byte[] buffer = null;
        ByteArrayOutputStream bos = null;
        try {
            InputStream inputStream = file.getInputStream();
            bos = new ByteArrayOutputStream(4096);
            byte[] b = new byte[4096];
            int n;
            while ((n = inputStream.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            file.getInputStream().close();
            bos.close();
            buffer = bos.toByteArray();
//            BASE64Encoder encoder = new BASE64Encoder();
//            base64photo = encoder.encode(buffer);
//            System.out.println("照片流64:" + encoder.encode(buffer));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bos != null) { bos.close(); }
            } catch (IOException e) {
            }
        }
        return buffer;
    }

    /**
     * 压缩图片
     * @param b 图片的字节流
     * @param newWidth 压缩的宽度
     * @param quality 压缩质量 0-1之间float类型
     * @return
     * @throws IOException
     */
    public static String resize(byte[] b,int newWidth, float quality){
        if (quality > 1) {
            throw new IllegalArgumentException("Quality has to be between 0 and 1");
        }
        String baseStr = "";
        ByteArrayOutputStream byteArrayOutputStream = null;
        try{
            ImageIcon ii = new ImageIcon(b);
            Image i = ii.getImage();
            Image resizedImage = null;

            int iWidth = i.getWidth(null);
            int iHeight = i.getHeight(null);

            if (iWidth > iHeight) {
                resizedImage = i.getScaledInstance(newWidth,(newWidth * iHeight)
                        / iWidth,  Image.SCALE_SMOOTH);
            } else {
                resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight,
                        newWidth, Image.SCALE_SMOOTH);
            }

            // This code ensures that all the pixels in the image are loaded.
            Image temp = new ImageIcon(resizedImage).getImage();

            // Create the buffered image.
            BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null),
                    temp.getHeight(null), BufferedImage.TYPE_INT_RGB);

            // Copy image to buffered image.
            Graphics g = bufferedImage.createGraphics();

            // Clear background and paint the image.
            g.setColor(Color.white);
            g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
            g.drawImage(temp, 0, 0, null);
            g.dispose();

            // Soften.
            float softenFactor = 0.05f;
            float[] softenArray = {0, softenFactor, 0, softenFactor,
                    1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0};
            Kernel kernel = new Kernel(3, 3, softenArray);
            ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
            bufferedImage = cOp.filter(bufferedImage, null);

            byteArrayOutputStream = new ByteArrayOutputStream(4096);
            // Encodes image as a JPEG data stream
            JPEGImageEncoder imgEncoder = JPEGCodec.createJPEGEncoder(byteArrayOutputStream);
            JPEGEncodeParam param = imgEncoder.getDefaultJPEGEncodeParam(bufferedImage);
            param.setQuality(quality, true);
            imgEncoder.setJPEGEncodeParam(param);
            imgEncoder.encode(bufferedImage);

            //转换成64字节码
            BASE64Encoder encoder = new BASE64Encoder();
            baseStr = encoder.encode(byteArrayOutputStream.toByteArray());
        }catch (IOException e){
            e.printStackTrace();
        }
//        File resizedFile = new File("/Users/jennifer/Documents/11111.jpg");
//        FileOutputStream out = new FileOutputStream(resizedFile);
//        out.write(byteArrayOutputStream.toByteArray());
//        out.close();
        return baseStr;
    } // Example usage





  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值