Android文件(视频、图片等)转Base64踩过的坑

说明:

1.图片还好,转Base64时没有出现啥大的问题.

2.视频转Base64时,打印出来的log日志   Base64码只有前半部分,后面相当一大部分base64码都没有.  一开始以为转码代码问题.

   解决方法(很狗血):

          在转完Base64码时,将Base64字符串写入到本地,在从本地中读取出来,这时的Base64码是一个完整的码,没有丢失的.

          注:为啥丢失没搞懂.

代码:

1.图片转Base64.

     /**
     * bitmap转成base64.
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

 

2.文件(File)转Base64:

方法一:   

注:这个方法是需要导入一个Jar包的,不然BASE64Encoder()报错.      jar包可以私聊我要(那些收费下载的 啥啥啥)。.

/**
 * 文件转Base64.
 * @param path
 * @return
 * @throws Exception
 */
public static String fileToBase64(String path) throws Exception {
    File file = new File(path);
    FileInputStream inputFile = new FileInputStream(file);
    byte[] buffer = new byte[(int) file.length()];
    inputFile.read(buffer);
    inputFile.close();
    return new BASE64Encoder().encode(buffer);
}

方法二:

注:这个方法不需要jar包

/**
 * 文件转Base64.
 * @param filePath
 * @return
 */
public static String file2Base64(String filePath) {
    FileInputStream objFileIS = null;
    try {
        objFileIS = new FileInputStream(filePath);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    ByteArrayOutputStream objByteArrayOS = new ByteArrayOutputStream();
    byte[] byteBufferString = new byte[1024];
    try {
        for (int readNum; (readNum = objFileIS.read(byteBufferString)) != -1; ) {
            objByteArrayOS.write(byteBufferString, 0, readNum);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    String videodata = Base64.encodeToString(objByteArrayOS.toByteArray(), Base64.DEFAULT);
    return videodata;
}

3.将字符串写入本地文件:

/**
 * 将字符串写入到指定文件.
 *
 * @param content
 * @param context
 */
public static void saveToFile(String content, Context context) {
    BufferedWriter out = null;

    //获取SD卡状态
    String state = Environment.getExternalStorageState();
    //判断SD卡是否就绪
    if (!state.equals(Environment.MEDIA_MOUNTED)) {
        Toast.makeText(context, "请检查SD卡", Toast.LENGTH_SHORT).show();
        return;
    }
    //取得SD卡根目录
    File file = Environment.getExternalStorageDirectory();
    try {
        if (file.exists()) {
            Log.e("print", "file路径:" + file.getCanonicalPath());
        }
        //输出流的构造参数1:可以是File对象  也可以是文件路径
        //输出流的构造参数2:默认为False=>覆盖内容; true=>追加内容
        out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(file.getCanonicalPath() + "/VideoBase64.txt",
                        true)));
        out.newLine();
        out.write(content);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

4.从本地文件读取内容:

/**
 * 从SD卡读取指定文件.
 *
 * @param context
 * @return
 */
public static String readFromFile(Context context) {
    //读的时候要用字符流   万一里面有中文
    BufferedReader reader = null;
    FileInputStream fis;
    StringBuilder sbd = new StringBuilder();
    String state = Environment.getExternalStorageState();
    if (!state.equals(Environment.MEDIA_MOUNTED)) {
        Toast.makeText(context, "SD卡未就绪", Toast.LENGTH_SHORT).show();
        return "";
    }
    File root = Environment.getExternalStorageDirectory();
    try {
        fis = new FileInputStream(root + "/VideoBase64.txt");
        reader = new BufferedReader(new InputStreamReader(fis));
        String row;
        while ((row = reader.readLine()) != null) {
            sbd.append(row);
        }
    } catch (FileNotFoundException e) {
        Toast.makeText(context, "文件不存在", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return sbd.toString();
}

版权声明:本文为GXL_1899原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。