问题描述
在我的Android应用程序,我需要在我的资产/可绘制/文件夹的原始上传图像到服务器。
我试过如下:
In my android application, I need to upload a image in my Assets/Drawable/raw folder to the server.I tried the following:
InputStream fileInputStream;
if(imageChanged) {
File file = New File("filename");
fileInputStream = new FileInputStream(file);
}else {
fileInputStream = ctx.getAssets().open("default.png");
}
int bytesAvailable;
byte[] buffer = new byte[102400];
while((bytesAvailable = fileInputStream.available()) > 0) {
int bufferSize = Math.min(bytesAvailable, 102400);
if(bufferSize<102400){
buffer = new byte[bufferSize];
}
int bytesRead = fileInputStream.read(buffer, 0,bufferSize);
dos.write(buffer, 0, bytesRead);
}
这执行罚款。我能够读取InputStream和写入字节到DataOutputStream类,图像上传到服务器。
This executes fine. I am able to read the inputstream and write bytes to the DataOutputStream, the image is uploaded to the server.
总之,在服务器上的形象似乎已损坏 - 只为默认的图像(在'其他'块上传的如果块图像不被损坏),
Anyhow, the image at the server appears to be corrupted - only for the default image (uploaded in the 'else' block. The 'if' block image is not getting corrupted)
我也试过将在原始的文件夹为Default.png,并试图下面
I also tried placing default.png in the 'raw' folder and tried the below
fileInputStream = ctx.getResources().openRawResource(R.drawable.default);
同样的结果在这里 - 在服务器图像被损坏。
Same result here - the image at the server is corrupted.
我开始怀疑这是因为为Default.png是在应用空间。
I am starting to doubt if this is because the default.png is in the application space.
我可以朝着正确的方法一定的帮助,上传应用空间的图像(绘/资产/ RAW)?
Can I get some help towards the proper way to upload an image in the application space (drawable/asset/raw)?
谢谢!
NIMI
推荐答案
这可能与缓冲区的大小呢?我尝试两种不同的方法来读取/写入从资产文件夹PNG两者产生的工作形象。我用的FileOutputStream写入SD卡,但不应该是一个问题。
It might have to do with the buffer size? I tried two different methods to read/write a png from the assets folder and both produced a working image. I used FileOutputStream to write to the sdcard but that should not be an issue.
InputStream is, is2;
FileOutputStream out = null, out2 = null;
try {
//method 1: compressing a Bitmap
is = v.getContext().getAssets().open("yes.png");
Bitmap bmp = BitmapFactory.decodeStream(is);
String filename = Environment.getExternalStorageDirectory().toString()+File.separator+"yes.png";
Log.d("BITMAP", filename);
out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
//method 2: Plain stream IO
String filename2 = Environment.getExternalStorageDirectory().toString()+File.separator+"yes2.png";
out2 = new FileOutputStream(filename2);
Log.d("BITMAP", filename2);
int r, i=0;
is2 = v.getContext().getAssets().open("yes.png");
while ((r = is2.read()) != -1) {
Log.d ("OUT - byte " + i, "Value: " + r);
out2.write(r);
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
if (out2 != null)
out2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
这篇关于从Android应用空间上传的图片似乎已损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!