2014-01-31 29 views
2

我要創建活動進這樣的:它可能在android中從MySQL數據庫中檢索圖像並將其顯示在imageview中?

Activity Feed

,我不知道,我將如何獲取圖像,以及如何將其存儲在我的MySQL數據庫。幫幫我!

+3

你必須保存在數據庫中只圖像路徑,並使用該路徑檢索 – Angel

+0

圖像是有可能。你可以把它保存爲byte []數組也可以保存圖像路徑或圖像名稱在數據庫和訪問它。 – Piyush

+0

如何使用php如何訪問它?我已經在我的cPanel中保存了一張圖片(這是一個主機/域名),我付了錢。 – IamAndroida

回答

0

這裏是一般步驟,如果你想將圖像本身存儲到數據庫中。

i。使用它的URL檢索圖像並將其保存在內存中作爲byte []。有幾種方法可以做到這一點,包括創建一個ByteArrayBuffer並在其末尾附加字節。然後,您可以使用ByteArrayBuffer.toByteArray()檢索最終字節[]。

ii。您需要創建一個包含BLOB類型列的表,例如

CREATE TABLE image (id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT, data BLOB) 

iii。然後,您可以像插入任何其他數據類型一樣插入圖像byte [],例如通過創建ContentValues並將其傳遞給SQLiteDatabase.insert()。

iv。從SQLite中檢索字節[]並構建一個圖像。使用Cursor.getBlob()來獲取的byte [],然後做:

ByteArrayInputStream byteArrayImageStream = new ByteArrayImageStream(yourByteArray); 
Bitmap yourImage = BitmapFactory.decodeStream(byteArrayImageStream); 
+0

這適用於使用託管數據庫嗎?即時通訊不使用SQLitedtabase,即時通訊使用MySQL數據庫,我也使用PHP作爲Android和MySQL之間的橋樑 – IamAndroida

+0

這是一個完全不同的場景,但它看起來完全可行。這裏是我找到的第一個鏈接,當我搜索「php下載圖像到mysql」時:http://www.phpriot.com/articles/images-in-mysql一旦你將圖像保存到MySQL中,你只需要讓你的Android應用程序調用PHP並獲取圖像。 – stackoverflowuser2010

2
  1. 下載圖像
  2. 保存爲字符串數據庫

這裏是如何做到這一點

  1. 爲了下載圖片使用Universal Image Loader

    ImageLoader imageLoader = ImageLoader.getInstance(); 
    imageLoader.init(ImageLoaderConfiguration.createDefault(context)); 
    OR 
    ImageLoaderConfiguration config = new 
        ImageLoaderConfiguration.Builder(context) 
        .maxImageWidthForMemoryCache(800) 
        .maxImageHeightForMemoryCache(480) 
        .httpConnectTimeout(5000) 
        .httpReadTimeout(20000) 
        .threadPoolSize(5) 
        .threadPriority(Thread.MIN_PRIORITY + 3) 
        .denyCacheImageMultipleSizesInMemory() 
        .build(); 
    imageLoader.init(config); 
    options = new DisplayImageOptions.Builder() 
        .showStubImage(R.drawable.loading) 
        .cacheInMemory() 
        .cacheOnDisc() 
        .build(); 
    imageLoader.displayImage(ProductsImageURL,imagView,options, new ImageLoadingListener(){}); 
    

在這個ImageLoadingListener你得到一個當加載完成,將圖像保存爲字符串

或作出任何HTTP連接到這裏下載圖片How to download and save an image in Android

  • 一旦圖像被下載其轉換成字符串,並將其存儲在數據庫

    public Bitmap StringToBitMap(String encodedString) { 
        try { 
         byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT); 
         Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, 
           encodeByte.length); 
         return bitmap; 
        } catch (Exception e) { 
         e.getMessage(); 
         return null; 
        } 
    } 
    
    public String BitMapToString(Bitmap bitmap) { 
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); 
        byte[] b = baos.toByteArray(); 
        String temp = Base64.encodeToString(b, Base64.DEFAULT); 
        return temp; 
    } 
    
  • 相關問題