序文:
Android 携帯電話クライアントの写真データはサーバーにアップロードされ、保存されますが、まずクライアントの写真データを Base64 形式に変換し、ネットワーク経由でサーバーにアップロードする必要があります。
これを実現するには 2 つの方法があります。
クライアントが画像をサーバーにアップロードし、画像のネットワーク URL をサーバーに伝えます。
画像を Base64 エンコードに変換してサーバーに渡すと、サーバーは Base64 文字列をデコードした後に画像を生成します。
この記事では、画像を Base64 に変換することに焦点を当てています。
Android は、util パッケージで android.util.Base64 クラスを提供します。
このクラスは、次の 4 つのエンコーディング メソッドを提供します。
public static byte[] encode(byte[] input, int flags)
public static byte[] encode(byte[] input, int offset, int len, int flags)
public static String encodeToString(byte[] input, int flags)
public static String encodeToString(byte[] input, int offset, int len, int flags)
3 つのデコードを提供します
public static byte[] decode(String str, int flags)
public static byte[] decode(byte[] input, int flags)
public static byte[] decode(byte[] input, int offset, int len, int flags)
4 つのエンコード方式のそれぞれに、エンコード フラグまたはエンコード標準である flags パラメータがあることがわかりました。
コーディング標準は次のとおりです。
CRLF
Win スタイルの改行文字は、Unix スタイルの LF の代わりに CR と LF のペアを行末として使用することを意味します。
CRLF は Carriage-Return Line-Feed の略で、キャリッジ リターン (\r) とライン フィード (\n) を意味します。
つまり、Windows スタイルの行末識別子は \r\n で、Unix スタイルの行末識別子は \n です。
デフォルト
このパラメータはデフォルトです。暗号化にはデフォルトの方法を使用します。
NO_PADDING
このパラメータは、暗号化文字列の末尾の「=」を省略します。
NO_WRAP
このパラメータはすべての改行を省略することを意味します(設定後はCRLFは無効になります)
URL_SAFE
このパラメータは、URL やファイル名に対して特別な意味を持つ文字が暗号化時に暗号化文字として使用されないことを意味します。具体的には、+ と / を - と _ に置き換えます。
NO_CLOSE
通常、`Base64OutputStream` とともに使用され、ラップされている出力ストリームを閉じるべきではないことを示すために `Base64OutputStream` に渡されるフラグです。
画像を Base64 に変換するコードは次のとおりです。
/**
* 将图片转换成Base64编码的字符串
*/
public static String imageToBase64(String path){
if(TextUtils.isEmpty(path)){
return null;
}
InputStream is = null;
byte[] data = null;
String result = null;
try{
is = new FileInputStream(path);
//创建一个字符流大小的数组。
data = new byte[is.available()];
//写入数组
is.read(data);
//用默认的编码格式进行编码
result = Base64.encodeToString(data,Base64.NO_CLOSE);
}catch (Exception e){
e.printStackTrace();
}finally {
if(null !=is){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
Base64画像変換コードは次のとおりです。
/**
* 将Base64编码转换为图片
* @param base64Str
* @param path
* @return true
*/
public static boolean base64ToFile(String base64Str,String path) {
byte[] data = Base64.decode(base64Str,Base64.NO_WRAP);
for (int i = 0; i < data.length; i++) {
if(data[i] < 0){
//调整异常数据
data[i] += 256;
}
}
OutputStream os = null;
try {
os = new FileOutputStream(path);
os.write(data);
os.flush();
os.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}catch (IOException e){
e.printStackTrace();
return false;
}
}