Android 图片压缩

添加Luban库  库地址:

//https://github.com/Curzibn/Luban
implementation 'top.zibin:Luban:1.1.8' //https://github.com/Curzibn/Luban

使用方法:

package com.example.sniffapplication.Utils;

import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;

import java.io.File;
import java.util.List;

import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class ImageUtil {
    //图片压缩
    public static void Compression(Context content, Uri uri, OnCompressListener compressListener) {
       String path=  FileUtil.getFilePathFromURI(content,uri);
        Luban.with(content)
                .load(path)
                .ignoreBy(100)
                .setTargetDir(getPath(content))
                .setCompressListener(compressListener).launch();
    }

    private static String getPath(Context content) {
        return content.getCacheDir().getPath();
    }
}
 private void CompressionImage(Uri uri, int imageIndex) {
        String realFileName = FileUtil.getFileRealNameFromUri(this, uri);
        ImageUtil.Compression(this, uri, new OnCompressListener() {
            @Override
            public void onStart() {
                // TODO 压缩开始前调用,可以在方法内启动 loading UI
            }

            @Override
            public void onSuccess(File file) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO 压缩成功后调用,返回压缩后的图片文件
                        UploadImage(file.getPath(), imageIndex,realFileName);
                    }
                });

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                // TODO 当压缩过程出现问题时调用
            }
        });

    }
 public static String getFilePathFromURI(Context context, Uri contentUri) {
        File rootDataDir = context.getExternalFilesDir(null);
//        MyApplication.getMyContext().getExternalFilesDir(null).getPath();
        String fileName = getFileName(contentUri);
        if (!TextUtils.isEmpty(fileName)) {
            File copyFile = new File(rootDataDir + File.separator + fileName);
            copyFile(context, contentUri, copyFile);
            return copyFile.getAbsolutePath();
        }
        return null;
    }

注意事项:load需要传入绝对路径 如果传入的是

android.net.Uri  压缩成功后返回的是一个空的File
posted @ 2021-10-03 11:43  _York  阅读(275)  评论(0编辑  收藏  举报