在我的应用程序的数据库中,我将gif图像存储为BLOB。我怎样才能从数据库中检索这个gif并将其保存为sdcard作为gif文件?对于png和jpeg我知道怎么做。如何在没有任何库的情况下正确实现此目的? 对于png和jpeg我喜欢这段代码:
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 :(得分:1)
ByteArrayInputStream imageStream = new ByteArrayInputStream(imageBlob);
一旦你有了,只需将流保存到文件。不要制作它的位图,也不要使用BitmapFactory。您可以将它用于png,jpg和gif。