如何簡單地利用Bitmap為中介儲存圖片到數據庫中


    這是我的第一篇博文,請大家多多指教!
    大概一個月之前,在跟朋友合作開發一個APP的過程中,我們發現到一個問題:圖片的存儲。因為數據庫沒有圖片這種數據類型,當用戶上傳的圖片需要存儲的時候,我們無法將其直接放進數據庫中。
    在經歷了幾天的探索,結合郭神的《第二行代碼》調用攝像頭拍照以及從相冊中選擇圖片這兩小節,我們發現了Android里面的一個圖片類:Bitmap。最終發現,利用Bitmap及其相關的工具類即可實現圖片的存儲以及顯示。

    主要用到的工具類:

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;

import java.io.ByteArrayOutputStream;

/**
 * Created by cartoon on 2017/12/9.
 */

public class StringAndBitmap {
    //圖片與String之間的轉換,便於將圖片存儲在數據庫中
    private Bitmap bitmap;
    private String string;
    public Bitmap stringToBitmap(String string){
        //數據庫中的String類型轉換成Bitmap
        if(string!=null){
            byte[] bytes= Base64.decode(string,Base64.DEFAULT);
            bitmap= BitmapFactory.decodeByteArray(bytes,0,bytes.length);
            return bitmap;
        }
        else {
            return null;
        }
    }
    public String bitmapToString(Bitmap bitmap){
        //用戶在活動中上傳的圖片轉換成String進行存儲
        if(bitmap!=null){
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] bytes = stream.toByteArray();// 轉為byte數組
            string=Base64.encodeToString(bytes,Base64.DEFAULT);
            return string;
        }
        else{
            return "";
        }
    }
}

    下面已經獲取到數據庫中已經存儲了的圖片的String語句string,只需要在需要顯示圖片的組件中調用關於顯示Bitmap的方法即可。

imageView.setImageBitmap(stringAndBitmap.stringToBitmap(string);
//這里的imageView為頁面組件綁定的ID,string為從數據庫獲取到圖片的string形態

    而存儲用戶上傳的圖片則需要這樣即可。

bitmap=((BitmapDrawable)imageView.getDrawable()).getBitmap();
string=stringAndBitmap.bitmapToString(bitmap);

    經過一些數據庫的操作,即可以把用戶上傳的圖片存入到數據庫中。
    因為數據庫部分不是我負責的,所以我的建議是數據庫中的類型選擇BLOB(MySQL),因為已經實現過是可行的。
    以上就是之前開發的一點小技巧,也是經過痛才領會出來的。我們還沒有測試過資源的消耗以及延時的情況,但確實是可以存儲圖片到數據庫中的。
    如果你們有任何對這篇博文的建議或者意見的話,歡迎私信或者在下方評論。最重要的是可以幫助到像我們一樣的入門者。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM