save Bitmap by CompressFormat - Android Graphics

Android examples for Graphics:Bitmap Compress

Description

save Bitmap by CompressFormat

Demo Code

/*Copyright (C) 2012 Crow Hou (crow_hou@126.com)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at/*  w w w. j a  v  a  2s  .c om*/

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/
//package com.java2s;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.graphics.Bitmap;

import android.graphics.Bitmap.CompressFormat;

public class Main {

    public static boolean saveBitmap(Bitmap bitmap, String file,
            CompressFormat format) {
        OutputStream os = null;
        try {
            File f = new File(file);
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }
            os = new BufferedOutputStream(new FileOutputStream(file));
            if (bitmap.compress(format, 100, os)) {
                os.flush();
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // do nothing
                }
            }
        }
        return false;
    }
}

Related Tutorials