将bitmap保存到sd卡

来源:互联网 发布:单片机汇编set 编辑:程序博客网 时间:2024/06/05 15:55
/**
 * Store image to SD card.
 */
private String storeImageToFile(Bitmap bitmap){
    if(bitmap == null){
        return null;
    }
 
    int count = 15;   //the number which will prevent the create segment locked.
    File file = null;
    RandomAccessFile accessFile = null;
    int MagicNum;
    String path = null;
     
    do{
        MagicNum = (int)mRandom.nextLong();
        path = path + "/" + String.valueOf(MagicNum) + ".png";
        file = new File(path);
        count--;
    }while(!file.exists() && count > 0);
     
    ByteArrayOutputStream steam = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, steam);
    byte[] buffer = steam.toByteArray();
 
    try {
        accessFile = new RandomAccessFile(file, "rw");
        accessFile.write(buffer);
    } catch (Exception e) {
        return null;
    }
     
    try {
        steam.close();
        accessFile.close();
    } catch (IOException e) {
        //Note: do nothing.
    }
     
    return path;
}
原创粉丝点击