android Java BASE64編碼和解碼二:圖片的編碼和解碼


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

  


免責聲明!

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



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