牛骨文教育服务平台(让学习变的简单)
博文笔记

Android保存Bitmap到本地

创建时间:2016-11-29 投稿人: 浏览次数:553
 private int i;

    public void saveMyBitmap(Bitmap mBitmap) {

        File dir = new File("/sdcard/Note/");
        if (!dir.exists())
            dir.mkdirs();
        File f = new File("/sdcard/Note/" + i++ + ".jpg");
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.e("FFF", e.getMessage());
        }
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("FFF", e.getMessage());
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("FFF", e.getMessage());
        }
    }

/**
     * @param bitmap  需要保存的图片对象
     * @param picPath 需要保存的本地路径,建议设置为公用常量
     */
    private void saveBitmap(Bitmap bitmap, String picPath) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(new File(picPath));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * @param imageView 需要设置图片的控件
     * @param picPath   需要读取图片的本地路径
     * @return
     */
    private void readBitmap(ImageView imageView, String picPath) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(new File(picPath));
            Bitmap bitmap = BitmapFactory.decodeStream(fis);
            imageView.setImageBitmap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (null != fis) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。