0
在我的android應用程序中,我想保存從服務器上傳到我的數據庫的一些照片,然後再使用它們。我想我應該將它們保存爲二進制格式並將其鏈接保存到數據庫中。這是更好的解決方案嗎?你能給一些代碼或例子嗎?謝謝。如何將從互聯網上傳的照片保存到數據庫中?
PS:現在我只上傳圖片並直接使用ImageView顯示,但我希望在用戶離線時使其在我的應用程序中可用。
在我的android應用程序中,我想保存從服務器上傳到我的數據庫的一些照片,然後再使用它們。我想我應該將它們保存爲二進制格式並將其鏈接保存到數據庫中。這是更好的解決方案嗎?你能給一些代碼或例子嗎?謝謝。如何將從互聯網上傳的照片保存到數據庫中?
PS:現在我只上傳圖片並直接使用ImageView顯示,但我希望在用戶離線時使其在我的應用程序中可用。
爲我的經驗做到這一點的最佳方法是保存我的圖像從互聯網到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卡獲取圖像。
感謝您的回覆。是否有可能將圖像存儲在/ data/data/package_name目錄中?我不想使用外部存儲,並依賴於SD卡的可用性。 – user435979 2010-09-01 14:16:56