安卓开发图片处理工具类

代码如下:

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import com.dijing.app.nanzhu.Constants;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;


/**
 * Created by wishes on 2018/7/13.
 */

public class ImageUtil {

    private static final String TAG = ImageUtil.class.getName();


    /**
     * 保存图片到本地+图库
     */
    public void saveImageToPhotos(Context context, Bitmap bmp,String fileName) {

        try {

        File appDir = new File(Environment.getExternalStorageDirectory(), Constants.APP_LOCAL_STORE);
        if (!appDir.exists()) {
            appDir.mkdir();
        }

        final File file = new File(appDir, fileName);

            // 把文件插入到系统图库

            //此方法当图片过大时会报oom异常,可能会导致程序崩溃
//          MediaStore.Images.Media.insertImage(context.getContentResolver(),
//                        file.getAbsolutePath(),"E"+timeStamp , null);
            //解决oom异常
            insertImage(context.getContentResolver(), fileName, file.getParent(),fileName+".jpg", bmp, null);

            // 通知图库更新
            updateAlbum(context,Uri.fromFile(new File(file.getPath()+".jpg")));
            LOG.i(TAG,"image save successfully.");
        } catch (Exception e) {
            LOG.e(TAG,"image save failed...");
            e.printStackTrace();
        }
    }


    /**
     * 通知系统图库更新
     */
    public void updateAlbum(Context context,Uri url){
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, url));
        LOG.i(TAG,"update album successfully.");
    }


    private Uri IMAGE_URI;

    public  Uri insertImage(ContentResolver cr, String fileName,
                                  String directory, String fileName2, Bitmap bmp, byte[] jpegData) {
        OutputStream outputStream = null;

        try {
            File dir = new File(directory);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(directory, fileName2);

            if(!file.exists()){
                if (file.createNewFile()) {
                    outputStream = new FileOutputStream(file);
                    if (bmp != null) {//压缩图片为jpg格式
                        bmp.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                    } else {
                        outputStream.write(jpegData);
                    }
                }
            }else{
                outputStream = new FileOutputStream(file);
                if (bmp != null) {
                    bmp.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                } else {
                    outputStream.write(jpegData);
                }
            }

            IMAGE_URI = Uri.fromFile(file);
        } catch (FileNotFoundException e) {
           e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (Throwable t) {
                }
            }
        }
        String filePath = directory + fileName2;
        // 系统时间
        long dateTaken = System.currentTimeMillis();
        ContentValues values = new ContentValues(7);
        values.put(MediaStore.Images.Media.TITLE, fileName);
        values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName2);
        values.put(MediaStore.Images.Media.DATE_TAKEN, dateTaken);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.Images.Media.DATA, filePath);

        return cr.insert(IMAGE_URI, values);
    }


}

 

应用示例:网络中下载图片保存到本地

1.下载图片子线程

 //创建并启动一个新线程用于从网络上下载图片
                        //这里必须新起一个线程,Android后面的版本中,不允许在主线程中联网
                        new Thread(){
                            @Override
                            public void run() {
                                try {
                                    LOG.i(TAG,loginUser.getPortrait());
                                    //创建一个url对象
                                    URL url=new URL(loginUser.getPortrait());

                                    //打开URL对应的资源输入流
                                    InputStream is= url.openStream();
                                    //从InputStream流中解析出图片
                                    bitmap = BitmapFactory.decodeStream(is);
                                    //  imageview.setImageBitmap(bitmap);
                                    //发送消息,通知UI组件显示图片
                                    handler.sendEmptyMessage(0x9527);
                                    //关闭输入流
                                    is.close();
                                    //------------------------------
                                    ImageUtil  imageUtil = new ImageUtil();
                                    //保存图片到本地和图库
                                    imageUtil.saveImageToPhotos(currentContext,bitmap,"portrait");

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }.start();

 

2.主线程中的Handle类,监听子线程的状态并做出相应处理

  private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what==0x9527) {
                //显示从网上下载的图片
                imageview.setImageBitmap(bitmap);
            }
        }
    };

 会不定期扩充和修改此类。

你可能感兴趣的:(安卓开发)