简体   繁体   English

Android Image Upload适用于相机,但不适用于图库

[英]Android Image Upload working for camera but not gallery

I am trying to get an image and upload it. 我正在尝试获取图像并上传。 This is always working for Camera but not working for images from gallery. 这始终适用于Camera,但不适用于图库中的图像。 It is failing with HTTP status of 422 and always succeeds for camera images with status code 201. 它以HTTP状态422失败,并且对于状态码为201的摄像机图像始终成功。

Here is my Image capture code: 这是我的图像捕获代码:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

Bitmap takenPictureData;

switch (imageUploadMethod) {
case Constants.SELECT_CAMERA:

try {
if (requestCode == Constants.SELECT_CAMERA && data != null) {
Bundle extras = data.getExtras();
if (extras!= null && extras.containsKey("data")) {
    takenPictureData = (Bitmap) extras.get("data");
    ImageView imageView = (ImageView) getActivity().findViewById(R.id.fragment_add_retailer_img_pic);
    imageView.setImageBitmap(takenPictureData);
    uploadImage(takenPictureData, false, retailer_profile_client_transacation_id);


    Log.d("IMAGE_ISSUE", "IMAGE BITMAP : " + takenPictureData);
}
}
} catch (Exception e) {
Log.d("Exception", "" + e.toString());
}
break;

case Constants.SELECT_GALLERY:
if (data != null) {
Uri selectedImageUri = data.getData();
takenPictureData = ImageUtils.getBitmapFromUri(getActivity(), selectedImageUri);

picCallBackImageView1.setImageBitmap(takenPictureData);
uploadImage(takenPictureData, false, retailer_profile_client_transacation_id);


Log.d("IMAGE_ISSUE", "IMAGE BITMAP : " + takenPictureData);
}
break;
}

This is the utility method: 这是实用程序方法:

public static Bitmap getBitmapFromUri(Context c, Uri uri)  {

        Bitmap image = null;
        try {
            ParcelFileDescriptor parcelFileDescriptor =
                    c.getContentResolver().openFileDescriptor(uri, "r");
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
            parcelFileDescriptor.close();
        }
        catch(IOException e){
            if (Constants.PRINT_DEBUG) {
                e.printStackTrace();
                Log.d("URI to Bitmap", "" + e.toString());
            }
        }
        return image;
    }

After getting the Bitmap, I am passing the byte array to my task // convert from bitmap to byte array 获得位图后,我将字节数组传递给任务//从位图转换为字节数组

  public static byte[] getBytesFromBitmap(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        return stream.toByteArray();
    }

And here is my HttpRequestImageUpload.java 这是我的HttpRequestImageUpload.java

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class HttpRequestImageUpload extends AsyncTask<byte[], Void, String> {

    Context context;
    private IRequestCallback callback;
    SuperActivity superActivity;
    SuperFragment superFragment;
    HttpPut httpPut;
    int client_transaction_id;
    String str;

    public IRequestCallback getCallback() {
        return callback;
    }

    public void setCallback(IRequestCallback callback) {
        this.callback = callback;
    }

    public HttpRequestImageUpload(SuperActivity superActivity, Context context , int client_transaction_id) {
        this.superActivity = superActivity;
        this.context = context;
        this.client_transaction_id = client_transaction_id;
    }

    public HttpRequestImageUpload(SuperFragment superFragment, Context context , int client_transaction_id) {
        this.superFragment = superFragment;
        this.context = context;
        this.client_transaction_id = client_transaction_id;
    }

    @Override
    protected String doInBackground(byte[]... params) {
        Log.d("IMAGE_ISSUE", "SENT FROM doInBackground() : " + params[0]);
        return upload(params[0]);
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Log.d("IMAGE_ISSUE", "On postExeceute() : " + s);
        if (s.equalsIgnoreCase("Error")) {
            callback.errorCallBack(s,str);
        } else {
            callback.imageUploadCallBack(s,str);
        }
    }

    @Override
    protected void onCancelled() {
        Log.d("IMAGE_ISSUE", "Cancelled in ImageUpload");
        try {
            if(httpPut != null) {
                httpPut.abort();
            }
        } catch (Exception e) {
            Crashlytics.logException(e);
        }
        super.onCancelled();
    }

    @Override
    protected void onCancelled(String s) {
        super.onCancelled(s);
    }

    public String upload(byte[] byteArrayEntity) {
        setCallback(superActivity != null ? superActivity : superFragment);
        Log.d("IMAGE_ISSUE", "UPLOADING : request " + byteArrayEntity);
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();


        HttpConnectionParams.setConnectionTimeout(client.getParams(), 120000);
        HttpConnectionParams.setSoTimeout(client.getParams(), 120000);

        httpPut = new HttpPut(CommonUtil.getBaseUrl()+"artefacts?type=Image&client_transaction_id="+client_transaction_id);
        httpPut.addHeader("Authorization", "Bearer " + Prefs.getToken(context));
        httpPut.addHeader("Content-Type", "application/octet-stream");
        httpPut.setEntity(new ByteArrayEntity(byteArrayEntity));

        try {
            HttpResponse response = client.execute(httpPut);
            Log.d("IMAGE_ISSUE", "UPLOADING : Response " + response);
            StatusLine statusLine = response.getStatusLine();
            Log.d("IMAGE_ISSUE", "UPLOADING : Status Line " + statusLine);
            int statusCode = statusLine.getStatusCode();
            Log.d("IMAGE_ISSUE", String.valueOf(statusCode));
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
            } else if (statusCode == 201) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
            } else {
                return ("Error");
            }
        } catch (Exception e) {
            Log.d("IMAGE_ISSUE", "Exception:  " + e.toString());
        }
        return stringBuilder.toString();
    }
}

Well...as I said ...this async task works well for all images captured from camera. 好吧...就像我说的那样...这个异步任务对于从相机捕获的所有图像都效果很好。 But in case of images taken from gallery.... the async task is not executing with 422 status. 但是,如果从图库中拍摄图像....异步任务不会以422状态执行。

This is a very common mistake..I don't know why I did not find any good resources to solve this issue...after looking around it for a few hours...I find that the When i am uploading image from gallery...the size comes out to be much larger than when i capture a bitmap using Camera. 这是一个非常常见的错误。.我不知道为什么找不到足够好的资源来解决这个问题...环顾了几个小时之后...我发现从画廊上传图片时...大小比我使用Camera捕获位图时要大得多。 The difference is around 50 times larger size for gallery... this is causing an issue with ImageUpload...resulting into 422 Status. 差异约为图库大小的50倍...这导致ImageUpload出现问题...结果为422状态。

Scaling the image in OnActivityResult() and then sending it to the ImageUploadAsyncTask... worked like charm. 在OnActivityResult()中缩放图像,然后将其发送到ImageUploadAsyncTask ...就像魅​​力一样。 Here is the method I used to scale the bitmap. 这是我用来缩放位图的方法。

public static Bitmap scaleImage(Context context, Uri photoUri) throws IOException {
        InputStream is = context.getContentResolver().openInputStream(photoUri);
        BitmapFactory.Options dbo = new BitmapFactory.Options();
        dbo.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(is, null, dbo);
        is.close();

        int rotatedWidth, rotatedHeight;
        int orientation = getOrientation(context, photoUri);

        if (orientation == 90 || orientation == 270) {
            rotatedWidth = dbo.outHeight;
            rotatedHeight = dbo.outWidth;
        } else {
            rotatedWidth = dbo.outWidth;
            rotatedHeight = dbo.outHeight;
        }

        Bitmap srcBitmap;
        is = context.getContentResolver().openInputStream(photoUri);
        if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) {
            float widthRatio = ((float) rotatedWidth) / ((float) MAX_IMAGE_DIMENSION);
            float heightRatio = ((float) rotatedHeight) / ((float) MAX_IMAGE_DIMENSION);
            float maxRatio = Math.max(widthRatio, heightRatio);

            // Create the bitmap from file
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = (int) maxRatio;
            srcBitmap = BitmapFactory.decodeStream(is, null, options);
        } else {
            srcBitmap = BitmapFactory.decodeStream(is);
        }
        is.close();

        /*
         * if the orientation is not 0 (or -1, which means we don't know), we
         * have to do a rotation.
         */
        if (orientation > 0) {
            Matrix matrix = new Matrix();
            matrix.postRotate(orientation);

            srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(),
                    srcBitmap.getHeight(), matrix, true);
        }

        String type = context.getContentResolver().getType(photoUri);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (type.equals("image/png")) {
            srcBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        } else if (type.equals("image/jpg") || type.equals("image/jpeg")) {
            srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        }
        byte[] bMapArray = baos.toByteArray();
        baos.close();
        return BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android Webview 从图库和相机上传图片,相机不工作 - Android Webview image upload from gallery and camera, camera not working 无法在Android 8和9中从相机和图库上传图片 - Not able to upload image from camera and gallery in Android 8 & 9 Android Webview从图库或相机上传图像 - Android Webview Upload Image from gallery or camera 用于从库中上传图像或在Android中捕获相机的库 - Library for upload image from gallery or camera capture in android 如何从相机或图库中获取图像并上传到 Android Q 中的服务器? - How to get image from camera or gallery and upload to server in Android Q? android webview 从画廊上传但不是从相机上传代码丢失? - android webview upload from gallery working but not from camera Code missing? 在 WebView 中从相机或图库上传图像 - Upload an Image from camera or gallery in WebView 从我的WebView中的相机或图库上传图像 - Upload an Image from camera or gallery in my WebView 从相机获取图像或从图库上传并在 ImageView (Android Studio) 中显示后,保存图像为 SharedPreferences - Save image is SharedPreferences after Image is get from camera or upload from gallery and display at ImageView (Android Studio) 如何在上传到服务器之前在android中调整/压缩相机图像或图库图像? - How to resize/compress a camera image or gallery image in android before upload to server?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM