2010-08-31 73 views
0

在我的android应用程序中,我想保存从服务器上传到我的数据库的一些照片,然后再使用它们。我想我应该将它们保存为二进制格式并将其链接保存到数据库中。这是更好的解决方案吗?你能给一些代码或例子吗?谢谢。如何将从互联网上传的照片保存到数据库中?

PS:现在我只上传图片并直接使用ImageView显示,但我希望在用户离线时使其在我的应用程序中可用。

回答

0

为我的经验做到这一点的最佳方法是保存我的图像从互联网到SD卡导致文件访问速度更快。

功能在我的SD卡创建我的图片目录...

public static File createDirectory(String directoryPath) throws IOException { 

    directoryPath = Environment.getExternalStorageDirectory().getAbsolutePath() + directoryPath; 
    File dir = new File(directoryPath); 
    if (dir.exists()) { 
     return dir; 
    } 
    if (dir.mkdirs()) { 
     return dir; 
    } 
    throw new IOException("Failed to create directory '" + directoryPath + "' for an unknown reason."); 
} 

例如:: createDirectory("/jorgesys_images/");

我用这个功能来从互联网上我的图片保存到我自己的文件夹到SD卡

private Bitmap ImageOperations(Context ctx, String url, String saveFilename) { 
    try {   
     String filepath=Environment.getExternalStorageDirectory().getAbsolutePath() + "/jorgesys_images/"; 
     File cacheFile = new File(filepath + saveFilename); 
     cacheFile.deleteOnExit(); 
     cacheFile.createNewFile(); 
     FileOutputStream fos = new FileOutputStream(cacheFile); 
     InputStream is = (InputStream) this.fetch(url); 

     BitmapFactory.Options options=new BitmapFactory.Options(); 
     options.inSampleSize = 8; 

     Bitmap bitmap = BitmapFactory.decodeStream(is); 
     bitmap.compress(CompressFormat.JPEG,80, fos); 
     fos.flush(); 
     fos.close(); 
     return bitmap; 

    } catch (MalformedURLException e) {   
        e.printStackTrace(); 
     return null; 
    } catch (IOException e) { 
        e.printStackTrace();   
     return null; 
    } 
} 

public Object fetch(String address) throws MalformedURLException,IOException { 
    URL url = new URL(address); 
    Object content = url.getContent(); 
    return content; 
} 

您将在您的imageView中使用此Bitmpap,当您脱机时,您将直接从您的SD卡获取图像。

+0

感谢您的回复。是否有可能将图像存储在/ data/data/package_name目录中?我不想使用外部存储,并依赖于SD卡的可用性。 – user435979 2010-09-01 14:16:56

相关问题