如何转换文件到byte []数组通过蓝牙套接字来发送Android中? [英] How to convert files to byte[] Array to send via Bluetooth socket in Android?

查看:129
本文介绍了如何转换文件到byte []数组通过蓝牙套接字来发送Android中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我有,我需要通过蓝牙套接字连接发送文件(图像/视频..等)的要求。现在用的蓝牙聊天的SDK作为指导的例子。我可以成功连接,但我有麻烦了SD卡转换文件的字节数组,所以我可以通过一个OutputStream写。

Good day, i have a requirement where i need to send files(image/videos.. etc) through a bluetooth socket connection. Am using the Bluetooth chat example in the SDK as a guideline. I can connect successfully, but am having trouble converting the files in the sdcard to byte array so i can write it via an outputStream.

我可以转换使用以下code图片:

i can convert images using the following code:

//After getting the imageId from the cursor object
 Bitmap bitmap = Media.getBitmap(getContentResolver(), imageUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();

bitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);
bytes[] bytes = baos.toByteArray();

但有麻烦转换视频或其他文件,我应该使用一个ObjectOutputStream的所有转换或有另一种方式,我可以做到这一点,因为我似乎无法一个FileOutputStream转换为字节数组?谢谢

but having trouble converting videos or other files, should i be using a ObjectOutputStream for all conversion or is there another way i can do this because i can't seem to convert a fileOutputStream to a byte Array? Thank you

推荐答案

使用 getContentResolver()。openInputStream(URI)来获得一个URI的InputStream。然后读取InputStream中的数据的数据从输入流转换为字节[]

use getContentResolver().openInputStream(uri) to get an InputStream from a URI. and then read the data from inputstream convert the data into byte[] from that inputstream

与下面code尝试

public byte[] readBytes(Uri uri) throws IOException {
          // this dynamically extends to take the bytes you read
        InputStream inputStream = getContentResolver().openInputStream(uri);
          ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

          // this is storage overwritten on each iteration with bytes
          int bufferSize = 1024;
          byte[] buffer = new byte[bufferSize];

          // we need to know how may bytes were read to write them to the byteBuffer
          int len = 0;
          while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
          }

          // and then we can return your byte array.
          return byteBuffer.toByteArray();
        }

这篇关于如何转换文件到byte []数组通过蓝牙套接字来发送Android中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆