我必须向服务器发送一些从相机中取出的JPEG文件。当然,他们只是通过文件流来做到这一点。我的代码(对于每个文件)如下所示:
struct3.put("type", "image/jpeg");
f = new File(fileName);
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buffer = new byte[(int)f.length()];
bis.read(buffer);
fis.close();
struct3.put("bits", buffer);
毕竟我发送了一个结构:
Object[] params3 = { bid, login, pass, struct3 };
Object response2 = client.send("my_function", params3);
当我发送小文件时,一切都是正确的,但是当文件较大时,我收到“Out of Memory Exception”。
我的解决方法是压缩JPEG文件:
struct3.put("type", "image/jpeg");
final Options opts = new Options();
opts.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeFile(fileName, opts);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] byteArray = stream.toByteArray();
struct3.put("bits", byteArray);
Object[] params3 = { bid, login, pass, struct3 };
Object response2 = client.send("my_function", params3);
但是这种方式在服务器端产生了一个错误: “JPEG文件过早结束”。
在发送之前有没有办法纠正JPEG文件? 我知道JPEG应该以EOI(0xff,0xfd)结束。
如何检查并进行更正?
答案 0 :(得分:0)
由于照片上传到WordPress并且只有跟踪是gdlib的警告,因此没有日志报告。警告包含:“JPEG文件过早结束”
虽然我解决了这个问题。我已经实现了过程检查,如果byteArray以0xFF,0xD9结尾,如果不是我添加两个字节:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] byteArray = stream.toByteArray();
int byteToSendSize = byteArray.length;
boolean proper = ((byteArray[byteArray.length-2])==((byte)0xff))
&& ((byteArray[byteArray.length-1])==((byte)0xd9));
if(!proper)
byteToSendSize +=2;
byte[] byteToSend = new byte[byteToSendSize];
for (int i = 0; i < byteArray.length; i++) {
byteToSend[i] = byteArray[i];
}
if(!proper){
byteToSend[byteArray.length] = (byte) 0xff;
byteToSend[byteArray.length+1] = (byte) 0xd9;
}
struct3.put("bits", byteToSend);