美文网首页
android将图片保存进数据库

android将图片保存进数据库

作者: 9dc31c71746b | 来源:发表于2019-02-20 11:04 被阅读0次

    最近有朋友项目需要保存图片到本地数据库,问我怎么做,刚好我之前接触过,其实就是简单的base64编码转换,下面介绍超详细超简单demo:
    首先放图,no图no bb:


    效果图.png

    第一步:创建工程,然后更改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>
    

    然后创建assest folder:


    创建assest目录.png

    创建之后将图片放入(其实也可以放入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 {
                //将其打开转换成数据流
                inputStream = mAssetManager.open("banner_img.png");
                //利用BitmapFactory将数据流进行转换成bitmap
                return BitmapFactory.decodeStream(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } finally {
                //最后别忘了关闭数据流
                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,第二个参数为压缩质量,我选择了原画质,也就是100,第三个参数传入outputstream去写入压缩后的数据
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //将获取到的outputstream转换成byte数组
            byte[] bytes = outputStream.toByteArray();
            //android.util包下有Base64工具类,直接调用,格式选择Base64.DEFAULT即可
            String str = Base64.encodeToString(bytes, Base64.DEFAULT);
            //打印数据,下面计算用
            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);
    
    
    效果动态图.gif
    最后让我们做个计算:
    可以看到动态图,有点模糊,打印出来的byte length长度是1664161byte,然后除两次1024,变成1.59M左右,原图是1.2M,至于为什么会变大,可以参考这篇文章:https://blog.csdn.net/sallay/article/details/3550740
    到这里你应该就明白了,存进数据库只需要把base64存进去就可以了,文章到这里结束,有后续问题我会追加。
    附Demo下载链接:
    链接:https://pan.baidu.com/s/1E6QStQ1dyn5HzkCQS98k0A 密码:kgsl

    相关文章

      网友评论

          本文标题:android将图片保存进数据库

          本文链接:https://www.haomeiwen.com/subject/ntnfyqtx.html