Android 安卓:上传图片

Android 安卓:上传图片,android,image,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 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模式,我看不到任何日志等

即使我将图片上传到应用程序中,每次我试图上传到网络上时,它都会崩溃


有人能帮我吗?

您的问题是因为内存不足:-

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

下面的解决方案在我这边效果很好

@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();  
功能压缩图像

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;
}       
函数计算示例大小

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;
}
函数从Exif获取方向

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

它能在所有设备上工作吗?因为我知道data.getData()有时有问题:)什么问题?我听说,在某些设备上它返回null,你应该检查data.getData()是否正确=null,否则您应该执行data.getExtras().get(“data”);-但如果它是对的,我会打电话给你