Android图像上传适用于相机,但不适用于画廊

Android图像上传适用于相机,但不适用于画廊,android,bitmap,image-uploading,Android,Bitmap,Image Uploading,我正在尝试获取一个图像并上传它。这始终适用于相机,但不适用于画廊中的图像。HTTP状态为422时失败,状态代码为201的相机图像始终成功 以下是我的图像捕获代码: @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Bitmap takenPictureData;

我正在尝试获取一个图像并上传它。这始终适用于相机,但不适用于画廊中的图像。HTTP状态为422时失败,状态代码为201的相机图像始终成功

以下是我的图像捕获代码:

@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;
}
这是实用方法:

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;
    }
获取位图后,我将字节数组传递给我的任务 //从位图到字节数组的转换

  public static byte[] getBytesFromBitmap(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        return stream.toByteArray();
    }
这是我的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();
    }
}
导入android.content.Context;
导入android.os.AsyncTask;
导入android.util.Log;
导入com.crashlytics.android.crashlytics;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.StatusLine;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.methods.HttpPut;
导入org.apache.http.entity.ByteArrayEntity;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.params.HttpConnectionParams;
导入java.io.BufferedReader;
导入java.io.InputStream;
导入java.io.InputStreamReader;
公共类HttpRequestImageUpload扩展异步任务{
语境;
私有IRequestCallback回调;
超活性超活性;
超碎片超碎片;
HttpPut-HttpPut;
int客户端\事务\ id;
字符串str;
公共IRequestCallback getCallback(){
返回回调;
}
公共void setCallback(IRequestCallback回调){
this.callback=回调;
}
公共HttpRequestImageUpload(超级活动超级活动、上下文上下文、int客户端\u事务\u id){
这个。超活性=超活性;
this.context=上下文;
this.client\u transaction\u id=client\u transaction\u id;
}
公共HttpRequestImageUpload(SuperFragment SuperFragment、上下文上下文、int客户端\u事务\u id){
this.superFragment=superFragment;
this.context=上下文;
this.client\u transaction\u id=client\u transaction\u id;
}
@凌驾
受保护的字符串doInBackground(字节[]…参数){
Log.d(“IMAGE_ISSUE”,“从doInBackground()发送):“+params[0]);
返回上传(参数[0]);
}
@凌驾
受保护的void onPostExecute(字符串s){
super.onPostExecute(s);
Log.d(“图像问题”,“在PostExecute()上:”+s);
如果(s.equalsIgnoreCase(“错误”)){
callback.errorCallBack(s,str);
}否则{
callback.imageUploadCallBack(s,str);
}
}
@凌驾
受保护的void onCancelled(){
日志d(“图像发布”,“图像上传中取消”);
试一试{
if(httpPut!=null){
httpPut.abort();
}
}捕获(例外e){
Crashlytics.logException(e);
}
super.onCancelled();
}
@凌驾
取消时受保护的空(字符串s){
super.onCancelled(s);
}
公共字符串上载(字节[]byteArrayEntity){
setCallback(superActivity!=null?superActivity:superFragment);
Log.d(“图像发布”、“上传:请求”+byteArrayEntity);
StringBuilder StringBuilder=新的StringBuilder();
HttpClient=new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),120000);
HttpConnectionParams.setSoTimeout(client.getParams(),120000);
httpPut=newhttpput(CommonUtil.getBaseUrl()+“artifacts?type=Image&client\u transaction\u id=“+client\u transaction\u id”);
httpPut.addHeader(“授权”、“承载者”+Prefs.getToken(上下文));
addHeader(“内容类型”、“应用程序/八位字节流”);
httpPut.setEntity(新的ByteArrayEntity(ByteArrayEntity));
试一试{
HttpResponse response=client.execute(httpPut);
日志d(“图像问题”,“上传:响应”+响应);
StatusLine StatusLine=response.getStatusLine();
日志d(“图像发布”,“上传:状态行”+状态行);
int statusCode=statusLine.getStatusCode();
Log.d(“IMAGE_ISSUE”,String.valueOf(statusCode));
如果(状态代码==200){
HttpEntity=response.getEntity();
InputStream内容=entity.getContent();
BufferedReader=新的BufferedReader(新的InputStreamReader(内容));
弦线;
而((line=reader.readLine())!=null){
stringBuilder.append(行);
}
}否则如果(状态代码==201){
HttpEntity=response.getEntity();
InputStream内容=entity.getContent();
BufferedReader=新的BufferedReader(新的InputStreamReader(内容));
弦线;
而((line=reader.readLine())!=null){
stringBuilder.append(行);
}
}否则{
返回(“错误”);
}
}捕获(例外e){
Log.d(“图像问题”,“异常:+e.toString());
}
返回stringBuilder.toString();
}
}

正如我所说的,这个异步任务适用于从相机捕获的所有图像。但如果是从画廊拍的照片。。。。异步任务未在422状态下执行

这是一个非常常见的错误..我不知道为什么我没有找到任何好的资源来解决这个问题..环顾四周几个小时后..我发现当我从gallery上传图像时..大小比我使用相机拍摄位图时大得多。不同的是,画廊的大小要大50倍左右。。。这导致ImageUpload出现问题…导致422状态

在OnActivityResult()中缩放图像,然后将其发送到ImageUploadAsyncTask。。。工作很有魅力。下面是我用来缩放位图的方法

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);
    }

在多媒体资料的切换情况下,您已添加takenPict