最近有朋友項目需要保存圖片到本地數(shù)據(jù)庫焰薄,問我怎么做,剛好我之前接觸過跟压,其實就是簡單的base64編碼轉換胰蝠,下面介紹超詳細超簡單demo:
首先放圖,no圖no bb:
效果圖.png
第一步:創(chuàng)建工程,然后更改main.xml樣式
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="@+id/ivShow"
android:layout_width="match_parent"
android:layout_height="200dp" />
<!--建議使用nestedscrollview,解決滑動沖突-->
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="200dp">
<!--由于base64編碼巨多茸塞,所以加個NestedScrollView加以滑動-->
<TextView
android:id="@+id/tvCode"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.v4.widget.NestedScrollView>
<Button
android:id="@+id/transferToBase"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="transfer"
android:text="將圖片轉換成base64" />
<Button
android:id="@+id/transferToBitmap"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="transfer"
android:text="將base64轉換成圖片" />
</LinearLayout>
然后創(chuàng)建assest folder:
創(chuàng)建assest目錄.png
創(chuàng)建之后將圖片放入(其實也可以放入drawable目錄,這里使用assest目錄):
assest目錄圖片.png
放入圖片之后就可以開始寫主程序:
package wiz.com.imagebase64demo;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
private ImageView mImageView;
private TextView mTextView;
private AssetManager mAssetManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
/**
* 初始化view
*/
private void initView() {
mImageView = findViewById(R.id.ivShow);
mTextView = findViewById(R.id.tvCode);
}
/**
* 這是在xml定義了transfer的onclick事件
*
* @param view
*/
public void transfer(View view) {
switch (view.getId()) {
case R.id.transferToBase:
mTextView.setText(imageToBase64(getAssestResource()));
break;
case R.id.transferToBitmap:
Bitmap bitmap = base64ToImage(mTextView.getText().toString());
mImageView.setImageBitmap(bitmap);
break;
}
}
/**
* 獲取assest目錄下的圖片資源
*
* @return
*/
private Bitmap getAssestResource() {
mAssetManager = getAssets();
InputStream inputStream = null;
try {
//將其打開轉換成數(shù)據(jù)流
inputStream = mAssetManager.open("banner_img.png");
//利用BitmapFactory將數(shù)據(jù)流進行轉換成bitmap
return BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
//最后別忘了關閉數(shù)據(jù)流
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 將bitmap轉換成byte,該過程時間較長,建議子線程運行,但是這里我為了setText躲庄,就放主線程了
*
* @param bitmap
* @return
*/
private String imageToBase64(Bitmap bitmap) {
//以防解析錯誤之后bitmap為null
if (bitmap == null)
return "解析異常";
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//此步驟為將bitmap進行壓縮,我選擇了原格式png钾虐,第二個參數(shù)為壓縮質量读跷,我選擇了原畫質,也就是100禾唁,第三個參數(shù)傳入outputstream去寫入壓縮后的數(shù)據(jù)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
//將獲取到的outputstream轉換成byte數(shù)組
byte[] bytes = outputStream.toByteArray();
//android.util包下有Base64工具類效览,直接調用,格式選擇Base64.DEFAULT即可
String str = Base64.encodeToString(bytes, Base64.DEFAULT);
//打印數(shù)據(jù)荡短,下面計算用
Log.i("MyLog", "imageToBase64: " + str.length());
return str;
}
/**
* 將base64轉成bitmap丐枉,該過程速度很快
*
* @param text
* @return
*/
private Bitmap base64ToImage(String text) {
//同樣的,用base64.decode解析編碼掘托,格式跟上面一致
byte[] bytes = Base64.decode(text, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
}
這里附上drawable目錄獲取bitmap方法:
Bitmap myLogo = BitmapFactory.decodeResource(context.getResources(), R.drawable.banner_img);
效果動態(tài)圖.gif
最后讓我們做個計算:
可以看到動態(tài)圖瘦锹,有點模糊,打印出來的byte length長度是1664161byte闪盔,然后除兩次1024,變成1.59M左右弯院,原圖是1.2M,至于為什么會變大泪掀,可以參考這篇文章:https://blog.csdn.net/sallay/article/details/3550740
到這里你應該就明白了听绳,存進數(shù)據(jù)庫只需要把base64存進去就可以了,文章到這里結束异赫,有后續(xù)問題我會追加椅挣。
附Demo下載鏈接:
鏈接:https://pan.baidu.com/s/1E6QStQ1dyn5HzkCQS98k0A 密碼:kgsl