1、准备工作

(1)在项目中集成 Base64 代码,集成方法见第一篇博文:android Java BASE64编码和解码一:基础

(2)添加 ImgHelper工具类

package com.app21;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.IOException;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Bitmap.CompressFormat;import android.util.Base64;import sun.misc.BASE64Decoder.encoder.BASE64Decoder;import sun.misc.BASE64Decoder.encoder.BASE64Encoder;public class ImgHelper  {    /**     * TODO:将byte数组以Base64方式编码为字符串     * @param bytes 待编码的byte数组     * @return 编码后的字符串     * */    public static String encode(byte[] bytes){        return new BASE64Encoder().encode(bytes);    }    /**     * TODO:将以Base64方式编码的字符串解码为byte数组     * @param encodeStr 待解码的字符串     * @return 解码后的byte数组     * @throws IOException      * */    public static byte[] decode(String encodeStr) throws IOException{        byte[] bt = null;          BASE64Decoder decoder = new BASE64Decoder();          bt = decoder.decodeBuffer(encodeStr);        return bt;    }    /**     * TODO:将两个byte数组连接起来后,返回连接后的Byte数组     * @param front 拼接后在前面的数组     * @param after 拼接后在后面的数组     * @return 拼接后的数组     * */    public static byte[] connectBytes(byte[] front, byte[] after){        byte[] result = new byte[front.length + after.length];        System.arraycopy(front, 0, result, 0, after.length);        System.arraycopy(after, 0, result, front.length, after.length);        return result;    }    /**     * TODO:将图片以Base64方式编码为字符串     * @param imgUrl 图片的绝对路径(例如:D:\\jsontest\\abc.jpg)     * @return 编码后的字符串     * @throws IOException      * */    public static String encodeImage(String imgUrl) throws IOException{        FileInputStream fis = new FileInputStream(imgUrl);        byte[] rs = new byte[fis.available()];        fis.read(rs);        fis.close();        return encode(rs);    }    /**     * 将Bitmap转换成字符串     * @param bitmap     * @return     */    public static String bitmaptoString(Bitmap bitmap) {        String string = null;        ByteArrayOutputStream bStream = new ByteArrayOutputStream();        bitmap.compress(CompressFormat.PNG, 100, bStream);        byte[] bytes = bStream.toByteArray();        string = Base64.encodeToString(bytes, Base64.DEFAULT);        return string;    }        /**     * 把byte数组转化成 bitmap对象     * @param b     * @return     */    public static Bitmap bytes2Bimap(byte[] b) {        if (b.length != 0) {            return BitmapFactory.decodeByteArray(b, 0, b.length);        } else {            return null;        }    }}

2、把drawable里面的 图片进行编码和解码
主要布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/container"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.app21.MainActivity"    tools:ignore="MergeRootFrame" >    <Button        android:id="@+id/bt"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="点击到Sd卡文件界面内" />    <ImageView        android:id="@+id/image1"        android:layout_width="100dp"        android:layout_height="100dp" /></LinearLayout>

主要代码:

package com.app21;import java.io.IOException;import java.io.InputStream;import android.app.Activity;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.drawable.BitmapDrawable;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;/** * @author admin * 对drawable里面的图片进行存取 */public class MainActivity extends Activity {    ImageView imageView1 ;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main );        imageView1 = (ImageView) findViewById( R.id.image1 ) ;        //得到bitmap流字符串        String bitmapString = ImgHelper.bitmaptoString( getBitmap() ) ;        try {            Bitmap bitmap = ImgHelper.bytes2Bimap( ImgHelper.decode( bitmapString )) ;            imageView1.setImageBitmap( bitmap ) ;        } catch (IOException e) {            e.printStackTrace();        }        Button button = (Button) findViewById( R.id.bt ) ;        button.setOnClickListener( new OnClickListener() {            @Override            public void onClick(View v) {                startActivity( new Intent( MainActivity.this , MainActivityFile.class ));            }        });    }    //得到bitmap    public Bitmap getBitmap(){        InputStream inputStream = getResources().openRawResource(R.drawable.ic_launcher );          BitmapDrawable drawable = new BitmapDrawable(inputStream);          Bitmap bitmap = drawable.getBitmap();          return bitmap ;    }}


3、对Sd卡中的图片进行编码和解码

主要布局

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2     xmlns:tools="http://schemas.android.com/tools" 3     android:layout_width="match_parent" 4     android:layout_height="match_parent" 5     android:orientation="vertical" 6     tools:ignore="MergeRootFrame" > 7  8     <ImageView 9         android:id="@+id/image_file"10         android:layout_width="wrap_content"11         android:layout_height="wrap_content" />12 13 </LinearLayout>

主要代码

package com.app21;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.widget.ImageView;public class MainActivityFile extends Activity {    ImageView imageView1 ;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_file  );        imageView1 = (ImageView) findViewById( R.id.image_file ) ;        String str  ;        //将图片转化为字符串        try {            str = ImgHelper.encodeImage( getFileName() );            Bitmap bitmap = ImgHelper.bytes2Bimap( ImgHelper.decode( str )) ;            imageView1.setImageBitmap( bitmap ) ;        } catch (IOException e) {            e.printStackTrace();        }    }    /**     * 把图片存到本地     * @return sd卡图片的路径     */    String getFileName(){        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.libingbing  );        File SpicyDirectory = new File("/sdcard/Images/");        SpicyDirectory.mkdirs();         String filename="/sdcard/Images/" + "test11111" + ".jpg";        FileOutputStream out = null ;        try {            out = new FileOutputStream(filename);            bmp.compress(Bitmap.CompressFormat.JPEG , 100 , out);        }catch (Exception e) {            e.printStackTrace();        }finally{            try {                out.flush();            }catch (IOException e){                e.printStackTrace();}        }try {            out.close();        } catch (IOException e){            e.printStackTrace();        }        out=null;        return filename ;    }}

4、注意事项 :

在对SD卡中的图片编码和解码是需要添加权限

    <!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 从SDCard读取数据权限 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


5、运行结果 :

6、项目下载地址:

http://download.csdn.net/detail/yanzi2015/8712419

7、其他图片Base64编码的相关博客

http://www.cnblogs.com/coco1s/p/4375774.html

更多相关文章

  1. Android期末项目(一)—— 解析二维数组对象
  2. Android下如何计算要显示的字符串所占的宽度和高度
  3. android 数据传输之JSON
  4. Android实现TextView字符串波浪式跳动
  5. Android(安卓)TextUtils类介绍
  6. android中AudioRecord采集音频的参数说明
  7. Android中的数据结构解析(四)SparseArray和ArrayMap
  8. 研究Android音视频-3-在Android设备上采集音视频并使用MediaCode
  9. Android培训班(46)

随机推荐

  1. Android(安卓)TV listView焦点平滑移动
  2. Android兼容性优化-Android(安卓)8.0设置
  3. android 文件存储注意点
  4. Android(安卓)Bitmap与String互转
  5. 屏幕方向android:screenOrientation
  6. 介绍两个Android开源项目:Android显示GIF
  7. Android(安卓)O 版本(Android(安卓)8.0) 存
  8. Android:自定义view实现动画
  9. 在服务器上使用 gradle 打包 android 源
  10. Android(安卓)PopupWindow工具类 (已解决