在我当前的应用程序中,我将图片发送到我的服务器。现在我有问题,这些图片有时太大了。在将图片发送到服务器之前缩小图片的最佳方法是什么。目前,我将图片的URI存储在数据库(/mnt/sdcard/DCIM/SF.png)中并将其发送到服务器。我想缩小图像的分辨率,以便它需要更少的磁盘空间。有没有办法在Android中转换图像?
有人可以帮我解决这个问题吗?
由于
答案 0 :(得分:0)
我使用以下代码将图像发送到服务器,这里我将图像转换为字节数组。首先,您需要从URI解码图像,然后将位图转换为字节数组。
从URI解码位图:
Bitmap imageToSend= decodeBitmap("Your URI");
解码URI的方法
Bitmap getPreview(URI uri) {
File image = new File(uri);
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getPath(), bounds);
if ((bounds.outWidth == -1) || (bounds.outHeight == -1))
return null;
int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
: bounds.outWidth;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = originalSize / THUMBNAIL_SIZE;
return BitmapFactory.decodeFile(image.getPath(), opts);
}
将图像发送到服务器的代码
try {
ByteArrayOutputStream bosRight = new ByteArrayOutputStream();
imageToSend.compress(CompressFormat.JPEG, 100, bosRight);
byte[] dataRight = bosRight.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("url to send");
ByteArrayBody babRight = new ByteArrayBody(dataRight,
"ImageName.jpg");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("params", babRight);
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
Log.v("Response value is", sResponse);
JSONObject postObj = new JSONObject(sResponse);
String successTag = postObj.getString("success");
if (successTag.equals("1")) {
imageDeletion();
} else {
}
}
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage());
}
答案 1 :(得分:0)
用于将图像发送到服务器,您可以在Base64
中对其进行编码,然后将Base64编码的字符串发送到服务器...
android中的base64类不支持编码,所以你必须下载Bae64 java类文件......你可以在这里得到它http://iharder.sourceforge.net/current/java/base64/
之后非常简单。例如
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.YOURIMAGE);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String encodedstring=Base64.encodeBytes(ba);
然后将编码的字符串作为普通名称值对
发送并在此链接http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/
中给出了一个很好的例子