图片压缩算法 3M压缩到200K

MainActivity:
package com.example.yasuo;
 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
 
public class MainActivity extends Activity {
 
        final String PATH = Environment.getExternalStorageDirectory()
                        + "/Bst/a.jpg";
 
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                init();
        }
 
        private void init() {
                try {
                        getThumbUploadPath(PATH,480);
                } catch (Exception e) {
                        Log.e("eeee", e.toString());
                }
        }
 
        private String getThumbUploadPath(String oldPath,int bitmapMaxWidth) throws Exception {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(oldPath, options);
                int height = options.outHeight;
                int width = options.outWidth;
                int reqHeight = 0;
                int reqWidth = bitmapMaxWidth;
                reqHeight = (reqWidth * height)/width;
                // 在内存中创建bitmap对象,这个对象按照缩放大小创建的
                options.inSampleSize = calculateInSampleSize(options, bitmapMaxWidth, reqHeight);
//                System.out.println("calculateInSampleSize(options, 480, 800);==="
//                                + calculateInSampleSize(options, 480, 800));
                options.inJustDecodeBounds = false;
                Bitmap bitmap = BitmapFactory.decodeFile(oldPath, options);
                //Log.e("asdasdas", "reqWidth->"+reqWidth+"---reqHeight->"+reqHeight);
                Bitmap bbb = compressImage(Bitmap.createScaledBitmap(bitmap, bitmapMaxWidth, reqHeight, false));
                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                                .format(new Date());
                return BitmapUtils.saveImg(bbb, MD5Utils.md5(timeStamp));
        }
 
        private int calculateInSampleSize(BitmapFactory.Options options,
                        int reqWidth, int reqHeight) {
                // Raw height and width of image
                final int height = options.outHeight;
                final int width = options.outWidth;
                int inSampleSize = 1;
 
                if (height > reqHeight || width > reqWidth) {
                        if (width > height) {
                                inSampleSize = Math.round((float) height / (float) reqHeight);
                        } else {
                                inSampleSize = Math.round((float) width / (float) reqWidth);
                        }
                }
                return inSampleSize;
        }
 
        private Bitmap compressImage(Bitmap image) {
 
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                image.compress(Bitmap.CompressFormat.JPEG, 80, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
                int options = 100;
                while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
                        options -= 10;// 每次都减少10
                        baos.reset();// 重置baos即清空baos
                        image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
                }
                ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
                Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
                return bitmap;
        }
 
}



BitmapUtils:
package com.example.yasuo;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
 
import android.graphics.Bitmap;
import android.os.Environment;
 
/**
 * 将bitmap保存在SD卡
 * @author xinruzhou
 *
 */
public class BitmapUtils {
 
        /**
         * 
         * @param b Bitmap
         * <a href="\"http://www.eoeandroid.com/home.php?mod=space&uid=7300\"" target="\"_blank\"">@return</a> 图片存储的位置
         * @throws FileNotFoundException 
         */
        public static String saveImg(Bitmap b,String name) throws Exception{
                String path = Environment.getExternalStorageDirectory().getPath()+File.separator+"test/headImg/";
                File mediaFile = new File(path + File.separator + name + ".jpg");
                if(mediaFile.exists()){
                        mediaFile.delete();
                         
                }
                if(!new File(path).exists()){
                        new File(path).mkdirs();
                }
                mediaFile.createNewFile();
                FileOutputStream fos = new FileOutputStream(mediaFile);
                b.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
                b.recycle();
                b = null;
                System.gc();
                return mediaFile.getPath();
        }
}


MD5Utils:
package com.example.yasuo;
 
import java.security.MessageDigest;
 
public class MD5Utils {
 
        /**
         * MD5加密
         * @param str 要加密的字符串
         * @return 加密后的字符串
         */
        public static String md5(String str) {
                MessageDigest md5 = null;
                try {
                        md5 = MessageDigest.getInstance("MD5");
                } catch (Exception e) {
                        e.printStackTrace();
                        return "";
                }
                char[] charArray = str.toCharArray();
                byte[] byteArray = new byte[charArray.length];
                for (int i = 0; i < charArray.length; i++) {
                        byteArray<i> = (byte) charArray<i>;
                }
                byte[] md5Bytes = md5.digest(byteArray);
                StringBuffer hexValue = new StringBuffer();
                for (int i = 0; i < md5Bytes.length; i++) {
                        int val = ((int) md5Bytes<i>) & 0xff;
                        if (val < 16) {
                                hexValue.append("0");
                        }
                        hexValue.append(Integer.toHexString(val));
                }
                return hexValue.toString();
        }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我来为你介绍一下用 Java 和 Vue 实现照片采集并压缩200k的页面的方式。 首先,我们需要使用 Vue 来开发前端页面,使用 Java 来开发后端接口。在前端页面中,我们可以使用 Vue 的组件化开发方式来实现照片采集并压缩的功能,具体步骤如下: 1. 引入 Vue 和 ElementUI 组件库,以及图片压缩插件 `compressorjs`。 ```html <!-- 引入 Vue --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <!-- 引入 ElementUI 组件库 --> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> <script src="https://unpkg.com/element-ui/lib/index.js"></script> <!-- 引入图片压缩插件 --> <script src="https://cdn.jsdelivr.net/npm/compressorjs@6.1.1/dist/compressor.esm.js"></script> ``` 2. 创建一个用于上传图片的组件 `UploadImage`,包含一个上传按钮和一个预览区域。 ```html <template> <div> <el-upload class="upload-demo" action="./upload" :on-success="handleSuccess" :show-file-list="false" :before-upload="beforeUpload" > <el-button size="small" type="primary">点击上传</el-button> </el-upload> <div class="image-preview" v-if="imageUrl"> <img :src="imageUrl"> </div> </div> </template> ``` 3. 在 `UploadImage` 组件的 `methods` 中定义上传前的钩子函数 `beforeUpload` 和上传成功的回调函数 `handleSuccess`。 ```js <script> export default { data() { return { imageUrl: '' // 保存上传成功后的图片地址 } }, methods: { beforeUpload(file) { // 使用图片压缩插件将图片压缩200k return new Promise(resolve => { new Compressor(file, { quality: 0.6, // 压缩质量 success(result) { resolve(result) } }) }) }, handleSuccess(response) { // 上传成功后保存图片地址 this.imageUrl = response.data.url } } } </script> ``` 4. 在 `UploadImage` 组件中使用 ElementUI 的样式美化上传按钮和预览区域。 ```css <style> .upload-demo { display: flex; justify-content: center; align-items: center; width: 200px; height: 200px; border: 1px dashed #ccc; border-radius: 4px; } .image-preview { margin-top: 10px; text-align: center; } .image-preview img { max-width: 100%; max-height: 200px; } </style> ``` 以上就是用 Vue 实现照片采集并压缩的前端部分。接下来,我们需要使用 Java 来开发后端接口,实现将上传的图片保存到服务器上。 1. 创建一个 Spring Boot 项目,并添加依赖 `spring-boot-starter-web` 和 `spring-boot-starter-tomcat`。 2. 创建一个上传图片的接口 `upload`,接收前端传来的图片,并将图片保存到服务器上。 ```java @RestController public class UploadController { @Value("${upload.path}") private String uploadPath; @PostMapping("/upload") public ResponseData upload(@RequestParam("file") MultipartFile file) throws IOException { if (file.isEmpty()) { return ResponseData.fail("上传文件不能为空"); } String fileName = file.getOriginalFilename(); String suffix = fileName.substring(fileName.lastIndexOf(".")); String newFileName = UUID.randomUUID() + suffix; File dest = new File(uploadPath + newFileName); file.transferTo(dest); return ResponseData.success("上传成功", new UploadResult(dest.getAbsolutePath())); } } ``` 其中,`uploadPath` 是我们在配置文件中配置的保存上传文件的路径。 3. 创建一个上传结果类 `UploadResult`,用于返回上传成功后的图片地址。 ```java public class UploadResult { private String url; public UploadResult(String path) { this.url = path; } // getter 和 setter 方法 } ``` 4. 创建一个统一的响应类 `ResponseData`,用于返回响应结果。 ```java public class ResponseData { private int code; private String message; private Object data; public ResponseData(int code, String message, Object data) { this.code = code; this.message = message; this.data = data; } public static ResponseData success(String message, Object data) { return new ResponseData(0, message, data); } public static ResponseData fail(String message) { return new ResponseData(-1, message, null); } // getter 和 setter 方法 } ``` 5. 在配置文件中配置上传文件保存的路径。 ```properties upload.path=/path/to/upload/dir/ ``` 以上就是用 Java 和 Vue 实现照片采集并压缩的方式,希望对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值