溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何利用Bitmap為中介儲存圖片到數(shù)據(jù)庫中

發(fā)布時間:2021-11-18 16:33:03 來源:億速云 閱讀:143 作者:小新 欄目:移動開發(fā)

這篇文章將為大家詳細(xì)講解有關(guān)如何利用Bitmap為中介儲存圖片到數(shù)據(jù)庫中,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

利用Bitmap及其相關(guān)的工具類即可實現(xiàn)圖片的存儲以及顯示。 

      主要用到的工具類:
     

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之間的轉(zhuǎn)換,便于將圖片存儲在數(shù)據(jù)庫中
    private Bitmap bitmap;
    private String string;
    public Bitmap stringToBitmap(String string){
        //數(shù)據(jù)庫中的String類型轉(zhuǎn)換成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){
        //用戶在活動中上傳的圖片轉(zhuǎn)換成String進(jìn)行存儲
        if(bitmap!=null){
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] bytes = stream.toByteArray();// 轉(zhuǎn)為byte數(shù)組
            string=Base64.encodeToString(bytes,Base64.DEFAULT);
            return string;
        }
        else{
            return "";
        }
    }
}

下面已經(jīng)獲取到數(shù)據(jù)庫中已經(jīng)存儲了的圖片的String語句string,只需要在需要顯示圖片的組件中調(diào)用關(guān)于顯示Bitmap的方法即可。

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

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

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

經(jīng)過一些數(shù)據(jù)庫的操作,即可以把用戶上傳的圖片存入到數(shù)據(jù)庫中。

因為數(shù)據(jù)庫部分不是我負(fù)責(zé)的,所以我的建議是數(shù)據(jù)庫中的類型選擇BLOB(MySQL),因為已經(jīng)實現(xiàn)過是可行的。

關(guān)于“如何利用Bitmap為中介儲存圖片到數(shù)據(jù)庫中”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI