我有一个Android应用程序,我正在尝试将图片发送到服务器.我使用Base64编码做到了这一点并且效果很好,但是在发送之前对图片进行编码需要太多的内存(和时间).
我试图将Android应用程序剥离到它只是简单地发送字节数组并且不会使用任何类型的编码方案,因此它将尽可能多地节省内存和CPU周期.
这就是我想要Android代码的样子:
public String sendPicture(byte[] picture, String address) {
try {
Socket clientSocket = new Socket(address, 8000);
OutputStream out = clientSocket.getOutputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out.write(picture);
return in.readLine();
}
catch(IOException ioe) {
Log.v("test", ioe.getMessage());
}
return " ";
}
Run Code Online (Sandbox Code Playgroud)
服务器是用Java编写的.如何编写服务器代码以便正确检索完全相同的字节数组?我的目标是尽可能多地在Android上保存CPU周期.
到目前为止,我尝试过的所有方法都会导致数据损坏或抛出异常.
任何帮助将不胜感激.
根据 Robert 和 Zaki 的评论,这里是修改后的代码,应该性能更好。
public byte[] getPicture(InputStream in) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int length = 0;
while ((length = in.read(data))!=-1) {
out.write(data,0,length);
}
return out.toByteArray();
} catch(IOException ioe) {
//handle it
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11869 次 |
| 最近记录: |