Android:上传图片

时间:2014-05-02 03:58:56

标签: android image

我有这样的代码:

Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT,null);
galleryIntent.setType("image/*");
galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);

Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 

Intent chooser = new Intent(Intent.ACTION_CHOOSER);
chooser.putExtra(Intent.EXTRA_INTENT, galleryIntent);      
chooser.putExtra(Intent.EXTRA_TITLE, "Continue with...");

Intent[] intentArray =  {cameraIntent}; 
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
chooser.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,mImageCaptureUri);
startActivityForResult(chooser,UPLOAD_IMAGE);

这允许我选择我想要上传图片的应用,然后

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == UPLOAD_IMAGE && resultCode == Activity.RESULT_OK){
        if(data.getData()!=null){
            try {
                Uri u= data.getData();
                InputStream stream = getContentResolver().openInputStream(u);
                Bitmap tmp = BitmapFactory.decodeStream(stream);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                tmp.compress(Bitmap.CompressFormat.JPEG, 60, out);
                Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

                stream.close();

                //Toast.makeText(this,"Uploaded "+(decoded.getByteCount())/1024/1024+"kb", Toast.LENGTH_LONG).show();

                bitmap = decoded;

                Cursor cursor = null;
                try { 
                  String[] proj = { MediaStore.Images.Media.DATA };
                  cursor = this.getContentResolver().query(u,  proj, null, null, null);
                  int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                  cursor.moveToFirst();
                  imageName = cursor.getString(column_index);

                  Toast.makeText(this, "Name: "+imageName, Toast.LENGTH_LONG).show();
                } finally {
                  if (cursor != null) {
                    cursor.close();
                  }
                }

            }
            catch (FileNotFoundException e){
                e.printStackTrace();
            }
            catch (IOException e){
                e.printStackTrace();
            }
        } 
        else 
        {
            Bitmap tmp = (Bitmap) data.getExtras().get("data"); 
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            tmp.compress(Bitmap.CompressFormat.JPEG, 60, out);
            Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

            String imageName = mImageCaptureUri.getPath();

            Toast.makeText(this, "Name: "+imageName, Toast.LENGTH_LONG).show();

            bitmap = decoded;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
    updateUploadedPictures();
}

最后,我试图通过以下代码将其上传到服务器:

public void uploadPhoto(Bitmap bitmap,String fileName, String country, String city) throws Exception {  
    try {  

       // HttpClient httpClient = new DefaultHttpClient();  
       // HttpContext localContext = new BasicHttpContext();  

        // here, change it to your php;  

        HttpPost httpPost = new HttpPost("http://www.one_f*****g_website.com");  
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
        bitmap = BitmapFactory.decodeFile(fileName);  


        ByteArrayOutputStream bos = new ByteArrayOutputStream();  
        bitmap.compress(CompressFormat.JPEG, 80, bos);  
        byte[] data = bos.toByteArray();  

        // sending a String param;  

        entity.addPart("user", new StringBody(USER.id));
        entity.addPart("country", new StringBody(country));
        entity.addPart("city", new StringBody(city));


        // sending a Image;  
        // note here, that you can send more than one image, just add another param, same rule to the String;  

        entity.addPart("image", new ByteArrayBody(data, USER.id));  

        httpPost.setEntity(entity);  
        //HttpResponse response = httpClient.execute(httpPost, localContext);  
        //BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent(), "UTF-8"));  
        //String sResponse = reader.readLine();  
    } catch (Exception e) {  
        Log.v("myApp", "Some error came up");  
    }  

}

我的问题是,应用程序崩溃了,但它并不是最糟糕的...... 有时,当我想从画廊中选择图片时,它说:没有可用的照片或视频......但是当我打开文件浏览器时,每一件事都在那里,之后它也出现在galery(有时候,应用程序刚刚崩溃)

因为我无法在debbug模式下使用它,所以我看不到任何LOG等...

即使我将图片上传到App,每当我尝试将其上传到网上时它都会崩溃

有人可以帮我一个忙吗?

1 个答案:

答案 0 :(得分:0)

你的问题发生是因为内存不足: -

Out of Memory error with Bitmap

您的应用程序有时会崩溃,因为当您的手机堆已满时,应用程序将崩溃。

解决方案在我的最后工作正常

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0)
        {
            if (resultCode == Activity.RESULT_OK)
            {
                try
                {
                    yourSelectedImage = null;// your bitmap
                    Uri selectedImageURI = data.getData();
                    File imageFile = new File(new ImageUtility(Activity.this).getRealPathFromURI(selectedImageURI));
                    ExifInterface exif;
                    exif = new ExifInterface(imageFile.toString());
                    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
                    yourSelectedImage = getOrientationFromExif(
                            compressImage(imageFile.toString(), (Activity.this)), orientation);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    yourSelectedImage.compress(Bitmap.CompressFormat.JPEG, 50, bos);
                    upload_foto.setImageBitmap(yourSelectedImage);
                    // scaleImage();

                }
                catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

现在制作图像字节数组

 ByteArrayOutputStream bos = new ByteArrayOutputStream();  
        yourSelectedImage.compress(CompressFormat.JPEG, 80, bos);  
        byte[] data = bos.toByteArray();  

function compressImage

public Bitmap compressImage(String imageUri, Activity act)
{
    String filePath = getRealPathFromURI(imageUri, act);

    BitmapFactory.Options options = new BitmapFactory.Options();

    // by setting this field as true, the actual bitmap pixels are not
    // loaded in the memory. Just the bounds are loaded. If
    // you try the use the bitmap here, you will get null.
    options.inJustDecodeBounds = true;
    // Bitmap bmp = decodeBitmap(Uri.parse(imageUri), 612, 816, act);
    Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
    // setting inSampleSize value allows to load a scaled down version of
    // the original image
    options.inSampleSize = calculateInSampleSize(options, 612, 816);

    // inJustDecodeBounds set to false to load the actual bitmap
    options.inJustDecodeBounds = false;

    // this options allow android to claim the bitmap memory if it runs low
    // on memory
    options.inPurgeable = true;
    options.inInputShareable = true;
    options.inTempStorage = new byte[16 * 1024];

        // load the bitmap from its path
    bmp = BitmapFactory.decodeFile(filePath, options);
    return bmp;
}       

function calculateInSampleSize

public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
{
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth)
    {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and
        // keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth)
        {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

function getOrientationFromExif

    public static Bitmap getOrientationFromExif(Bitmap bitmap, int orientation)
    {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int newWidth = 612;
        int newHeight = 816;

        // calculate the scale - in this case = 0.4f
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        switch (orientation)
        {
            case ExifInterface.ORIENTATION_NORMAL:
                return bitmap;
            case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
//              matrix.setScale(-1, 1);
                matrix.postScale(scaleWidth, scaleHeight);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                matrix.setRotate(180);
                break;
            case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                matrix.setRotate(180);
//              matrix.postScale(-1, 1);
                matrix.postScale(scaleWidth, scaleHeight);
                break;
            case ExifInterface.ORIENTATION_TRANSPOSE:
                matrix.setRotate(90);
//              matrix.postScale(-1, 1);
                matrix.postScale(scaleWidth, scaleHeight);
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                matrix.setRotate(90);
                break;
            case ExifInterface.ORIENTATION_TRANSVERSE:
                matrix.setRotate(-90);
//              matrix.postScale(-1, 1);
                matrix.postScale(scaleWidth, scaleHeight);
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                matrix.setRotate(-90);
                break;
            default:
                return bitmap;
        }
        try
        {
            Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            bitmap.recycle();
            return bmRotated;
        }
        catch (OutOfMemoryError e)
        {
            e.printStackTrace();
            return null;
        }
    }

<强> ImageUtility.java

public class ImageUtility
{
    private Context context;
    public ImageUtility(Context context)
    {
        this.context=context;
    }

    public String getRealPathFromURI(Uri contentURI)
    {
        String result;
        Cursor cursor = context.getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null)
        { // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        }
        else
        {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }
    }