tags:

views:

41

answers:

1

Hello, in my android application,I want to save some photos uploaded from a server on my database and then reuse them later. I think I should save them in a binary format and save their links into the database. Is it the better solution? Can you give some code or an example? Thanks.

PS: now I only uploaded the image and display it directly using an ImageView but I want to make it available in my application when the user is offline.

A: 

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.

Jorgesys
thanks for the response. is it possible to store images in the /data/data/package_name directory? i don't want use external storage and depend on the availibilty of the sdcard.