0

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

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

4

1 回答 1

0

for my experience the best way to do achieve this is savin my images from internet to the sdcard cause the file access is faster.

function to create my images directory in my sdcard...

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.");
}

example:: createDirectory("/jorgesys_images/");

I use this functions to save my images from internet to my own folder into the sdcard

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;
}

you will use this Bitmpap into your imageView, and when you are offline you will get the images directly from your sdcard.

于 2010-08-31T16:39:55.920 回答