从下面的代码我可以在我的移动应用程序中将图像文件转换为字节数组。但是由于 OutOfMemoryError 异常,我无法转换视频文件。我想将视频文件发送到arduino板。由于我可以从Android应用程序发送一个字符串到arduino,我正在尝试发送这样的视频文件。但它失败了。我还有其他解决方案来解决我的问题吗?请帮助。
将图像转换为字节数组的代码
func share() {
let textToShare = "Hello Pinterest!"
let url = URL(string: "http://blank.org")!
let imageToShare = UIImage(named: "so-logo")!
let activityItems: [Any] = [textToShare, url, imageToShare]
let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
}
通过USB线缆将字符串发送到arduino的代码
package com.example.krishan.detectusbplugin;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File file = new File(Environment.getExternalStorageDirectory() + "/Output/" +"My.mp4");
// convertFileToByteArray(file);
System.out.println(Arrays.toString(convertFileToByteArray(file)));
try {
System.out.write(convertFileToByteArray(file));
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[] convertFileToByteArray(File f) {
byte[] byteArray = null;
try {
InputStream inputStream = new FileInputStream(f);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024 * 8];
int bytesRead = 0;
while ((bytesRead = inputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byteArray = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return byteArray;
}
}