我一直在尝试查看压缩图像的其他示例。但是,我仍然不知道在哪里以及如何包含压缩代码。有人可以帮帮我吗?
public void uploadMultipart() {
//getting name for the image
String name = editText.getText().toString().trim();
//getting the actual path of the image
String path = getPath(filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//method to get the file path from uri
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
// Bitmap bmp = BitmapFactory.decodeFile(path);
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
cursor.close();
return path;
}
答案 0 :(得分:0)
以下是Bitmap
中压缩图像的代码下面是jpeg图片的代码
Bitmap bitmap = BitmapFactory.decodeStream(getAssets().open("imagename.png"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); // you can set as 90 for compress ration
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
下面是png图片的代码:
Bitmap bitmap= BitmapFactory.decodeStream(getAssets().open("imagename.png"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
否则,这是编码字符串并以编码格式图像发送到服务器的代码
String encodedString ="";
try {
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 1;
bitmap = BitmapFactory.decodeFile(filepath, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedString = Base64.encodeToString(byte_arr, 0);
} catch (Exception e) {
e.printStackTrace();
}
尝试以上解决方案。它对我有用。