[英]take photo and upload it to server without any compress android
我正在嘗試從設備相機拍攝照片或從圖庫中拾取圖片並通過齊射將其上傳到服務器,但一切正常,但圖像質量很差
private void dispatchTakePictureIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent , CAMERA_REQUEST_CODE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data {
switch (requestCode) {
case CAMERA_REQUEST_CODE:
if ( resultCode == RESULT_OK){
Bundle bundle = data.getExtras();
bitmap = (Bitmap) bundle.get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
}
break;
和getParams方法:
byte[] a = convertBitmapToByteArrayUncompressed(bitmap);
params.put("img" , Base64.encodeToString(a , Base64.DEFAULT));
public static byte[] convertBitmapToByteArrayUncompressed(Bitmap bitmap){
ByteBuffer byteBuffer = ByteBuffer.allocate(bitmap.getByteCount());
bitmap.copyPixelsToBuffer(byteBuffer);
byteBuffer.rewind();
return byteBuffer.array();
}
您應該使用多部分實體來發送圖像而不進行壓縮。 使用多部分實體,您的圖像質量也將得到保持。 請按照此步驟使用截擊發送圖像
public class MultipartReq extends JsonObjectRequest {
private static final String FILE_PART_NAME = "file";
private static final String STRING_PART_NAME = "text";
private final File mFilePart;
//private final String mStringPart;
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
HttpEntity httpEntity;
Context context;
private Map<String, String> params;
public MultipartReq(Context context, int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, File file, Map<String, String> params) {
super(method, url, jsonRequest, listener, errorListener);
this.context = context;
mFilePart = file;
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
this.params = params;
buildMultipartEntity();
httpEntity = entityBuilder.build();
}
private void buildMultipartEntity() {
try {
if (mFilePart.exists()) { entityBuilder.addBinaryBody(FILE_PART_NAME, mFilePart, ContentType.create(mimeType), mFilePart.getName());
}
try {
if(!params.isEmpty()){
for (String key: params.keySet()){
entityBuilder.addPart(key, new StringBody(params.get(key),ContentType.TEXT_PLAIN));
}
}
} catch (Exception e) {
VolleyLog.e("UnsupportedEncodingException");
}
} else {
ShowLog.e("no such file");
}
} catch (Exception e) {
ShowLog.e("UnsupportedEncodingException");
}
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
return params;
}
@Override
public String getBodyContentType() {
return httpEntity.getContentType().getValue();
}
@Override
public byte[] getBody() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpEntity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected void deliverResponse(JSONObject response) {
super.deliverResponse(response);
}
}
來自Naugat拍照會有所不同。
創建一個圖像文件拳頭:
String mCurrentPhotoPath;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
然后派遣拍照意圖
static final int REQUEST_TAKE_PHOTO = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
...
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
在onActivity結果中,檢查RESULT_OK是否成功捕獲。
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK)
您已經有了圖像路徑。 現在使用mCurrentPhotoPath
上傳過程。
另外,您需要實現文件提供程序。
在清單中添加以下內容:
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
...
</application>
在資源目錄中的XML中,添加以下內容:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>
現在,您將從照相機中獲取完整尺寸的圖像。
資料來源: https : //developer.android.com/training/camera/photobasics.html
對於小尺寸圖像,請使用getParcelableExtra()
而不是getExtras()
。
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("data");
如果圖像太大,則必須將其壓縮並發送到其他活動。 然后,您可以獲取壓縮的位圖並在第二個活動中將其解壓縮。 嘗試下面的代碼。
第一活動
Intent intent = new Intent(this, SecondActivity.class);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
byte[] bytes = stream.toByteArray();
intent.putExtra("bitmap",bytes);
第二活動
byte[] bytes = getIntent().getByteArrayExtra("bitmap");
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.