将文件转为byte[],通过ByteArrayOutputStream 实现
2016-05-05 09:34
477 查看
通过文件路径 转换byte[] 通过ByteArrayOutputStream 实现
/** * 将文件转为byte[] * @param filePath 文件路径 * @return */ public static byte[] getBytes(String filePath){ File file = new File(filePath); ByteArrayOutputStream out = null; try { FileInputStream in = new FileInputStream(file); out = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int i = 0; while ((i = in.read(b)) != -1) { out.write(b, 0, b.length); } out.close(); in.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } byte[] s = out.toByteArray(); return s; }
将bitmap对象 转为byte[] 并进行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; }
相关文章推荐
- PHP里还有这些好用的技巧
- 禁止解析 php
- YII 学习之 控制器传值到模板
- 安装 php
- yii2超好用的日期组件和时间组件
- yii2超好用的日期组件和时间组件
- PHP5.3x不再支持ereg和eregi
- 速战速决 (3) - PHP: 函数基础, 函数参数, 函数返回值, 可变函数, 匿名函数, 闭包函数, 回调函数
- ucwords.php
- 每天laravel-20160731| Container -3
- ucfirst.php
- 每天laravel-20160731| Container -3
- strtoupper2.php
- strtolower.php
- php ltrim()函数rtim()函数
- Laravel应用简单好用的多级联动插件cxSelect
- php trim()函数
- php-5.5.27安装
- PHP strftime() 函数
- Laravel5.2多图上传的实现以及上传七牛