开发者

How to save a photo uploaded from internet on a database?

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 e开发者_如何转开发xample? 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜