2014-10-27 73 views
0

在我的應用程序的數據庫中,我已經存儲了一個GIF圖像作爲BLOB。我如何從數據庫中檢索這個gif,並將其保存爲sdcard作爲gif文件?對於PNG和JPEG,我知道如何去做。我怎樣才能正確實現這個沒有任何圖書館? 對PNG和JPEG我做這樣的代碼:Android從數據庫保存GIF文件

ByteArrayInputStream imageStream; 
imageStream = new ByteArrayInputStream(imageBlob); 
Bitmap image= BitmapFactory.decodeStream(imageStream); 
storeImage(image); 


private void storeImage(Bitmap image) { 
    File pictureFile = getOutputMediaFile(); 
    if (pictureFile == null) 
    { 
     return; 
    } 
    try { 
     FileOutputStream fos = new FileOutputStream(pictureFile); 
     image.compress(Bitmap.CompressFormat.PNG, 90, fos); 
     fos.close(); 
    } catch (FileNotFoundException e) { 
     Log.i("MyApp", "File not found: " + e.getMessage()); 
    } catch (IOException e) { 
     Log.i("MyApp", "Error accessing file: " + e.getMessage()); 
    } 
} 

//To Get the Path for Image Storage 
private File getOutputMediaFile(){ 

    File mediaStorageDir = new File(Environment.getExternalStorageDirectory() 
      + "/Android/data/" 
      + contexto.getPackageName() 
      + "/Files"); 


    // Create the storage directory if it does not exist 
    if (! mediaStorageDir.exists()){ 
     if (! mediaStorageDir.mkdirs()){ 
      return null; 
     } 
    } 

    // Create a media file name 
    File mediaFile; 

    String mImageName="myImage.png"; 
    mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName); 

    return mediaFile; 
} 

我沒有成功嘗試以下。這不會創建該文件。我不知道什麼是錯,或者如果我錯過了什麼。

ByteArrayInputStream imageStream = new ByteArrayInputStream(imageBlob); 
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); 
int bufferSize = 1024; 
byte[] buffer = new byte[bufferSize]; 
int len = 0; 
while ((len = imageStream.read(buffer)) != -1) { 
     byteBuffer.write(buffer, 0, len); 
} 
FileOutputStream stream = new FileOutputStream(myPath); 
stream.write(byteBuffer.toByteArray()); 

需要幫助。提前致謝。

+0

什麼是數據庫中的圖像格式? – Henry 2014-10-27 12:38:45

+0

gif在數據庫中存儲爲BLOB。我想檢索它並保存到文件。 – user3065901 2014-10-27 13:05:52

+0

是的,但是如何在該blob中編碼像素? – Henry 2014-10-27 15:25:24

回答

1
ByteArrayInputStream imageStream = new ByteArrayInputStream(imageBlob); 

一旦你有,只需將流保存到文件。不要製作它的位圖,也不要使用BitmapFactory。你可以將它用於png,jpg和gif。

+0

查看更新後的問題 – user3065901 2014-10-27 16:57:29