1.创建byte的输出流。 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(8192);
2.通过设备本地路径获取一张bitmap图片信息。 Bitmap imageBitmap = BitmapFactory.decodeFile(imagePath);
3.关联Bitmap和输出流;
imageBitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
4.转换生成byte数组; byte [] bytes =byteArrayOutputStream.toByteArray();
如果要将byte数组转成pfd的话,可以用以下方法:
- pfd = writeToMemoryFile(bytes);
-
- private ParcelFileDescriptor writeToMemoryFile(byte[] bytes) {
- Log.d(TAG,"tongfei writeToMemoryFile ");
- MemoryFile memoryFile = null;
- try {
- memoryFile = new MemoryFile("data", bytes.length);
- memoryFile.writeBytes(bytes, 0, 0, bytes.length);
- // 需要反射调用
- Method getFileDescriptorMethod = memoryFile.getClass().getDeclaredMethod("getFileDescriptor");
- if (getFileDescriptorMethod != null) {
- FileDescriptor fileDescriptor = (FileDescriptor) getFileDescriptorMethod.invoke(memoryFile);
- // 序列化,才可传送
- return ParcelFileDescriptor.dup(fileDescriptor);
- }
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- }finally {
- if (memoryFile != null) {
- memoryFile.close();
- }
- }
- return null;
- }