Example usage for android.media ExifInterface TAG_ORIENTATION

List of usage examples for android.media ExifInterface TAG_ORIENTATION

Introduction

In this page you can find the example usage for android.media ExifInterface TAG_ORIENTATION.

Prototype

String TAG_ORIENTATION

To view the source code for android.media ExifInterface TAG_ORIENTATION.

Click Source Link

Document

Type is int.

Usage

From source file:com.stfalcon.contentmanager.ContentManager.java

/**
 * Some devices return wrong rotated image so we can fix it by this method
 *///from ww  w .j  a va2 s . com
public static void fixImageRatation(Uri uri, Bitmap realImage) {
    File pictureFile = new File(uri.getPath());

    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        ExifInterface exif = new ExifInterface(pictureFile.toString());

        if (exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("6")) {
            realImage = rotate(realImage, 90);
        } else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("8")) {
            realImage = rotate(realImage, 270);
        } else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("3")) {
            realImage = rotate(realImage, 180);
        }

        boolean bo = realImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);

        fos.close();

        Log.d("Info", bo + "");

    } catch (FileNotFoundException e) {
        Log.d("Info", "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d("TAG", "Error accessing file: " + e.getMessage());
    }
}

From source file:com.tealeaf.TeaLeaf.java

protected void onActivityResult(int request, int result, Intent data) {
    super.onActivityResult(request, result, data);
    PluginManager.callAll("onActivityResult", request, result, data);
    logger.log("GOT ACTIVITY RESULT WITH", request, result);

    switch (request) {
    case PhotoPicker.CAPTURE_IMAGE:
        if (result == RESULT_OK) {
            EventQueue.pushEvent(new PhotoBeginLoadedEvent());
            Bitmap bmp = null;// w  w  w  . j  a  va  2s  .  c  o m

            if (data != null) {
                Bundle extras = data.getExtras();
                //try and get bitmap off of intent
                if (extras != null) {
                    bmp = (Bitmap) extras.get("data");
                }

            }

            //try the large file on disk
            final File f = PhotoPicker.getCaptureImageTmpFile();
            if (f != null && f.exists()) {
                new Thread(new Runnable() {
                    public void run() {
                        Bitmap bmp = null;
                        String filePath = f.getAbsolutePath();

                        try {
                            bmp = BitmapFactory.decodeFile(filePath);
                        } catch (OutOfMemoryError e) {
                            System.gc();
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inSampleSize = 4;
                            bmp = BitmapFactory.decodeFile(filePath, options);
                        }

                        if (bmp != null) {
                            try {
                                File f = new File(filePath);
                                ExifInterface exif = new ExifInterface(f.getAbsolutePath());
                                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                                        ExifInterface.ORIENTATION_NORMAL);
                                if (orientation != ExifInterface.ORIENTATION_NORMAL) {
                                    int rotateBy = 0;
                                    switch (orientation) {
                                    case ExifInterface.ORIENTATION_ROTATE_90:
                                        rotateBy = ROTATE_90;
                                        break;
                                    case ExifInterface.ORIENTATION_ROTATE_180:
                                        rotateBy = ROTATE_180;
                                        break;
                                    case ExifInterface.ORIENTATION_ROTATE_270:
                                        rotateBy = ROTATE_270;
                                        break;
                                    }
                                    Bitmap rotatedBmp = rotateBitmap(bmp, rotateBy);
                                    if (rotatedBmp != bmp) {
                                        bmp.recycle();
                                    }
                                    bmp = rotatedBmp;
                                }
                            } catch (Exception e) {
                                logger.log(e);
                            }
                            f.delete();

                            if (bmp != null) {
                                glView.getTextureLoader()
                                        .saveCameraPhoto(glView.getTextureLoader().getCurrentPhotoId(), bmp);
                                glView.getTextureLoader().finishCameraPicture();
                            } else {
                                glView.getTextureLoader().failedCameraPicture();
                            }
                        }
                    }
                }).start();

            } else {
                glView.getTextureLoader().saveCameraPhoto(glView.getTextureLoader().getCurrentPhotoId(), bmp);
                glView.getTextureLoader().finishCameraPicture();
            }
        } else {
            glView.getTextureLoader().failedCameraPicture();
        }
        break;
    case PhotoPicker.PICK_IMAGE:
        if (result == RESULT_OK) {
            final Uri selectedImage = data.getData();
            EventQueue.pushEvent(new PhotoBeginLoadedEvent());

            String[] filePathColumn = { MediaColumns.DATA, MediaStore.Images.ImageColumns.ORIENTATION };

            String _filepath = null;

            try {
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                _filepath = cursor.getString(columnIndex);
                columnIndex = cursor.getColumnIndex(filePathColumn[1]);
                int orientation = cursor.getInt(columnIndex);
                cursor.close();
            } catch (Exception e) {

            }

            final String filePath = _filepath;

            new Thread(new Runnable() {
                public void run() {
                    if (filePath == null) {
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        InputStream inputStream;
                        Bitmap bmp = null;

                        try {
                            inputStream = getContentResolver().openInputStream(selectedImage);
                            bmp = BitmapFactory.decodeStream(inputStream, null, options);
                            inputStream.close();
                        } catch (Exception e) {
                            logger.log(e);

                        }

                        if (bmp != null) {
                            glView.getTextureLoader()
                                    .saveGalleryPicture(glView.getTextureLoader().getCurrentPhotoId(), bmp);
                            glView.getTextureLoader().finishGalleryPicture();
                        } else {
                            glView.getTextureLoader().failedGalleryPicture();
                        }

                    } else {
                        Bitmap bmp = null;

                        try {
                            bmp = BitmapFactory.decodeFile(filePath);
                        } catch (OutOfMemoryError e) {
                            System.gc();
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inSampleSize = 4;
                            bmp = BitmapFactory.decodeFile(filePath, options);
                        }

                        if (bmp != null) {
                            try {
                                File f = new File(filePath);
                                ExifInterface exif = new ExifInterface(f.getAbsolutePath());
                                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                                        ExifInterface.ORIENTATION_NORMAL);
                                if (orientation != ExifInterface.ORIENTATION_NORMAL) {
                                    int rotateBy = 0;
                                    switch (orientation) {
                                    case ExifInterface.ORIENTATION_ROTATE_90:
                                        rotateBy = ROTATE_90;
                                        break;
                                    case ExifInterface.ORIENTATION_ROTATE_180:
                                        rotateBy = ROTATE_180;
                                        break;
                                    case ExifInterface.ORIENTATION_ROTATE_270:
                                        rotateBy = ROTATE_270;
                                        break;
                                    }
                                    Bitmap rotatedBmp = rotateBitmap(bmp, rotateBy);
                                    if (rotatedBmp != bmp) {
                                        bmp.recycle();
                                    }
                                    bmp = rotatedBmp;
                                }
                            } catch (Exception e) {
                                logger.log(e);
                            }

                            if (bmp != null) {
                                glView.getTextureLoader()
                                        .saveGalleryPicture(glView.getTextureLoader().getCurrentPhotoId(), bmp);
                                glView.getTextureLoader().finishGalleryPicture();
                            } else {
                                glView.getTextureLoader().failedGalleryPicture();
                            }
                        }
                    }
                }
            }).start();

        } else {
            glView.getTextureLoader().failedGalleryPicture();
        }
        break;
    }
}

From source file:com.mobantica.DriverItRide.activities.ActivityProfile.java

private void previewCapturedImage() {
    try {//from w  w  w .java 2 s . co  m
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), ChnagedUri);
        if (bitmap != null) {
            ExifInterface ei = null;
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    InputStream in = getContentResolver().openInputStream(ChnagedUri);
                    ei = new ExifInterface(in);
                } else {
                    ei = new ExifInterface(ChnagedUri.getPath());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (ei != null) {
                int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_UNDEFINED);
                switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    bitmap = rotateImage(bitmap, 90);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    bitmap = rotateImage(bitmap, 180);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    bitmap = rotateImage(bitmap, 270);
                    break;
                }
            }

            Bitmap imageBitmap;
            imageBitmap = Bitmap.createScaledBitmap(AppUtils.resizeAndCropCenter(bitmap, 250, true), 250, 250,
                    false);
            img_profile_square.setImageBitmap(imageBitmap);

            imagebaseProfilephoto = Generic.convertBitmapToByteStrem(imageBitmap);
            task = new ActivityProfile.UpdateProfilePhotoTask();
            task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
        }
    } catch (IOException e) {
        e.printStackTrace();
        //Set default image here
    }
}

From source file:com.phonegap.plugins.wsiCameraLauncher.WsiCameraLauncher.java

/**
 * Called when the camera view exits.//from  w w  w.j av a  2 s . co  m
 * 
 * @param requestCode
 *            The request code originally supplied to
 *            startActivityForResult(), allowing you to identify who this
 *            result came from.
 * @param resultCode
 *            The integer result code returned by the child activity through
 *            its setResult().
 * @param intent
 *            An Intent, which can return result data to the caller (various
 *            data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // Get src and dest types from request code
    int srcType = (requestCode / 16) - 1;
    int destType = (requestCode % 16) - 1;
    int rotate = 0;

    Log.d(LOG_TAG, "-z");

    // If retrieving photo from library
    if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
        Log.d(LOG_TAG, "-y");
        if (resultCode == Activity.RESULT_OK) {
            Log.d(LOG_TAG, "-x");
            Uri uri = intent.getData();
            Log.d(LOG_TAG, "-w");
            // If you ask for video or all media type you will automatically
            // get back a file URI
            // and there will be no attempt to resize any returned data
            if (this.mediaType != PICTURE) {
                Log.d(LOG_TAG, "mediaType not PICTURE, so must be Video");

                String metadataDateTime = "";
                ExifInterface exif;
                try {
                    exif = new ExifInterface(this.getRealPathFromURI(uri, this.cordova));
                    if (exif.getAttribute(ExifInterface.TAG_DATETIME) != null) {
                        Log.d(LOG_TAG, "z4a");
                        metadataDateTime = exif.getAttribute(ExifInterface.TAG_DATETIME).toString();
                        metadataDateTime = metadataDateTime.replaceFirst(":", "-");
                        metadataDateTime = metadataDateTime.replaceFirst(":", "-");
                    }
                } catch (IOException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                }

                Log.d(LOG_TAG, "before create thumbnail");
                Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(
                        (new File(this.getRealPathFromURI(uri, this.cordova))).getAbsolutePath(),
                        MediaStore.Images.Thumbnails.MINI_KIND);
                Log.d(LOG_TAG, "after create thumbnail");
                String mid = generateRandomMid();

                try {
                    String filePathMedium = this.getTempDirectoryPath(this.cordova.getActivity()) + "/medium_"
                            + mid + ".jpg";
                    FileOutputStream foMedium = new FileOutputStream(filePathMedium);
                    bitmap.compress(CompressFormat.JPEG, 100, foMedium);
                    foMedium.flush();
                    foMedium.close();

                    bitmap.recycle();
                    System.gc();

                    JSONObject mediaFile = new JSONObject();
                    try {
                        mediaFile.put("mid", mid);
                        mediaFile.put("mediaType", "video");
                        mediaFile.put("filePath", filePathMedium);
                        mediaFile.put("filePathMedium", filePathMedium);
                        mediaFile.put("filePathThumb", filePathMedium);
                        mediaFile.put("typeOfPluginResult", "initialRecordInformer");
                        String absolutePath = (new File(this.getRealPathFromURI(uri, this.cordova)))
                                .getAbsolutePath();
                        mediaFile.put("fileExt", absolutePath.substring(absolutePath.lastIndexOf(".") + 1));
                        if (metadataDateTime != "") {
                            mediaFile.put("metadataDateTime", metadataDateTime);
                        }
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "error: " + e.getStackTrace().toString());
                    }
                    Log.d(LOG_TAG, "mediafile at 638" + mediaFile.toString());
                    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK,
                            (new JSONArray()).put(mediaFile));
                    pluginResult.setKeepCallback(true);
                    this.callbackContext.sendPluginResult(pluginResult);
                    new UploadVideoToS3Task().execute(new File(this.getRealPathFromURI(uri, this.cordova)),
                            this.callbackContext, mid, mediaFile);
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } else {
                String imagePath = this.getRealPathFromURI(uri, this.cordova);
                String mimeType = FileUtils.getMimeType(imagePath);
                // If we don't have a valid image so quit.
                if (imagePath == null || mimeType == null || !(mimeType.equalsIgnoreCase("image/jpeg")
                        || mimeType.equalsIgnoreCase("image/png"))) {
                    Log.d(LOG_TAG, "I either have a null image path or bitmap");
                    this.failPicture("Unable to retrieve path to picture!");
                    return;
                }

                String mid = generateRandomMid();

                Log.d(LOG_TAG, "a");

                JSONObject mediaFile = new JSONObject();

                Log.d(LOG_TAG, "b");

                try {
                    FileInputStream fi = new FileInputStream(imagePath);
                    Bitmap bitmap = BitmapFactory.decodeStream(fi);
                    fi.close();

                    Log.d(LOG_TAG, "z1");

                    // try to get exif data
                    ExifInterface exif = new ExifInterface(imagePath);

                    Log.d(LOG_TAG, "z2");

                    JSONObject metadataJson = new JSONObject();

                    Log.d(LOG_TAG, "z3");

                    /*
                    JSONObject latlng = new JSONObject();
                    String lat = "0";
                    String lng = "0";
                    if (exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE) != null) {
                       lat = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
                    }
                    if (exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE) != null) {
                       lng = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
                    }
                    latlng.put("lat", lat);
                    latlng.put("lng", lng);
                    Log.d(LOG_TAG, "z4");
                    metadataJson.put("locationData", latlng);
                    */

                    String metadataDateTime = "";

                    if (exif.getAttribute(ExifInterface.TAG_DATETIME) != null) {
                        Log.d(LOG_TAG, "z4a");
                        JSONObject exifWrapper = new JSONObject();
                        exifWrapper.put("DateTimeOriginal",
                                exif.getAttribute(ExifInterface.TAG_DATETIME).toString());
                        exifWrapper.put("DateTimeDigitized",
                                exif.getAttribute(ExifInterface.TAG_DATETIME).toString());
                        metadataDateTime = exif.getAttribute(ExifInterface.TAG_DATETIME).toString();
                        metadataDateTime = metadataDateTime.replaceFirst(":", "-");
                        metadataDateTime = metadataDateTime.replaceFirst(":", "-");
                        Log.d(LOG_TAG, "z5");
                        metadataJson.put("Exif", exifWrapper);
                    }
                    Log.d(LOG_TAG, "z6");

                    Log.d(LOG_TAG, "metadataJson: " + metadataJson.toString());
                    Log.d(LOG_TAG, "metadataDateTime: " + metadataDateTime.toString());

                    if (exif.getAttribute(ExifInterface.TAG_ORIENTATION) != null) {
                        int o = Integer.parseInt(exif.getAttribute(ExifInterface.TAG_ORIENTATION));

                        Log.d(LOG_TAG, "z7");

                        if (o == ExifInterface.ORIENTATION_NORMAL) {
                            rotate = 0;
                        } else if (o == ExifInterface.ORIENTATION_ROTATE_90) {
                            rotate = 90;
                        } else if (o == ExifInterface.ORIENTATION_ROTATE_180) {
                            rotate = 180;
                        } else if (o == ExifInterface.ORIENTATION_ROTATE_270) {
                            rotate = 270;
                        } else {
                            rotate = 0;
                        }

                        Log.d(LOG_TAG, "z8");

                        Log.d(LOG_TAG, "rotate: " + rotate);

                        // try to correct orientation
                        if (rotate != 0) {
                            Matrix matrix = new Matrix();
                            Log.d(LOG_TAG, "z9");
                            matrix.setRotate(rotate);
                            Log.d(LOG_TAG, "z10");
                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                    matrix, true);
                            Log.d(LOG_TAG, "z11");
                        }
                    }

                    Log.d(LOG_TAG, "c");

                    String filePath = this.getTempDirectoryPath(this.cordova.getActivity()) + "/econ_" + mid
                            + ".jpg";
                    FileOutputStream foEcon = new FileOutputStream(filePath);
                    fitInsideSquare(bitmap, 850).compress(CompressFormat.JPEG, 45, foEcon);
                    foEcon.flush();
                    foEcon.close();

                    Log.d(LOG_TAG, "d");

                    String filePathMedium = this.getTempDirectoryPath(this.cordova.getActivity()) + "/medium_"
                            + mid + ".jpg";
                    FileOutputStream foMedium = new FileOutputStream(filePathMedium);
                    makeInsideSquare(bitmap, 320).compress(CompressFormat.JPEG, 55, foMedium);
                    foMedium.flush();
                    foMedium.close();

                    Log.d(LOG_TAG, "e");

                    String filePathThumb = this.getTempDirectoryPath(this.cordova.getActivity()) + "/thumb_"
                            + mid + ".jpg";
                    FileOutputStream foThumb = new FileOutputStream(filePathThumb);
                    makeInsideSquare(bitmap, 175).compress(CompressFormat.JPEG, 55, foThumb);
                    foThumb.flush();
                    foThumb.close();

                    bitmap.recycle();
                    System.gc();

                    Log.d(LOG_TAG, "f");

                    mediaFile.put("mid", mid);
                    mediaFile.put("mediaType", "photo");
                    mediaFile.put("filePath", filePath);
                    mediaFile.put("filePathMedium", filePath);
                    mediaFile.put("filePathThumb", filePath);
                    mediaFile.put("typeOfPluginResult", "initialRecordInformer");
                    //mediaFile.put("metadataJson", metadataJson);
                    if (metadataDateTime != "") {
                        mediaFile.put("metadataDateTime", metadataDateTime);
                    }

                    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK,
                            (new JSONArray()).put(mediaFile));
                    pluginResult.setKeepCallback(true);
                    this.callbackContext.sendPluginResult(pluginResult);
                    Log.d(LOG_TAG, "g");
                    Log.d(LOG_TAG, "mediaFile " + mediaFile.toString());
                    new UploadFilesToS3Task().execute(new File(filePath), new File(filePathMedium),
                            new File(filePathThumb), this.callbackContext, mid, mediaFile);
                    Log.d(LOG_TAG, "h");
                } catch (FileNotFoundException e) {
                    Log.d(LOG_TAG, "error: " + e.getStackTrace().toString());
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    Log.d(LOG_TAG, "error: " + e1.getStackTrace().toString());
                } catch (JSONException e2) {
                    // TODO Auto-generated catch block
                    Log.d(LOG_TAG, "error: " + e2.getStackTrace().toString());
                }

                /*
                if (this.correctOrientation) {
                   String[] cols = { MediaStore.Images.Media.ORIENTATION };
                   Cursor cursor = this.cordova
                .getActivity()
                .getContentResolver()
                .query(intent.getData(), cols, null, null,
                      null);
                   if (cursor != null) {
                      cursor.moveToPosition(0);
                      rotate = cursor.getInt(0);
                      cursor.close();
                   }
                   if (rotate != 0) {
                      Matrix matrix = new Matrix();
                      matrix.setRotate(rotate);
                      bitmap = Bitmap.createBitmap(bitmap, 0, 0,
                   bitmap.getWidth(), bitmap.getHeight(),
                   matrix, true);
                   }
                }
                        
                // Create an ExifHelper to save the exif
                // data that is lost during compression
                String resizePath = this
                      .getTempDirectoryPath(this.cordova
                   .getActivity())
                      + "/resize.jpg";
                ExifHelper exif = new ExifHelper();
                try {
                   if (this.encodingType == JPEG) {
                      exif.createInFile(resizePath);
                      exif.readExifData();
                      rotate = exif.getOrientation();
                   }
                } catch (IOException e) {
                   e.printStackTrace();
                }
                        
                OutputStream os = new FileOutputStream(
                      resizePath);
                bitmap.compress(Bitmap.CompressFormat.JPEG,
                      this.mQuality, os);
                os.close();
                        
                // Restore exif data to file
                if (this.encodingType == JPEG) {
                   exif.createOutFile(this
                .getRealPathFromURI(uri,
                      this.cordova));
                   exif.writeExifData();
                }
                        
                if (bitmap != null) {
                   bitmap.recycle();
                   bitmap = null;
                }
                System.gc();
                        
                // The resized image is cached by the app in
                // order to get around this and not have to
                // delete your
                // application cache I'm adding the current
                // system time to the end of the file url.
                this.callbackContext.success("file://" + resizePath + "?" + System.currentTimeMillis());
                */
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Selection cancelled.");
        } else {
            this.failPicture("Selection did not complete!");
        }
    }
}

From source file:com.netcompss.ffmpeg4android_client.BaseWizard.java

@SuppressWarnings("unused")
private String reporteds(String path) {

    ExifInterface exif = null;//  w w w .j  a  va  2 s .c  o  m
    try {
        exif = new ExifInterface(path);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
    Matrix matrix = new Matrix();
    if (orientation == 6) {
        matrix.postRotate(90);
    } else if (orientation == 3) {
        matrix.postRotate(180);
    } else if (orientation == 8) {
        matrix.postRotate(270);
    }

    if (path != null) {

        if (path.contains("http")) {
            try {
                URL url = new URL(path);
                HttpGet httpRequest = null;

                httpRequest = new HttpGet(url.toURI());

                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);

                HttpEntity entity = response.getEntity();
                BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
                InputStream input = bufHttpEntity.getContent();

                Bitmap bitmap = BitmapFactory.decodeStream(input);
                input.close();
                return getPath(bitmap);
            } catch (MalformedURLException e) {
                Log.e("ImageActivity", "bad url", e);
            } catch (Exception e) {
                Log.e("ImageActivity", "io error", e);
            }
        } else {
            Options options = new Options();
            options.inSampleSize = 2;
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeResource(getApplicationContext().getResources(), srcBgId, options);
            options.inJustDecodeBounds = false;
            options.inSampleSize = calculateInSampleSize(options, w, h);
            Bitmap unbgbtmp = BitmapFactory.decodeResource(getApplicationContext().getResources(), srcBgId,
                    options);
            Bitmap unrlbtmp = ScalingUtilities.decodeFile(path, w, h, ScalingLogic.FIT);
            unrlbtmp.recycle();
            Bitmap rlbtmp = null;
            if (unrlbtmp != null) {
                rlbtmp = ScalingUtilities.createScaledBitmap(unrlbtmp, w, h, ScalingLogic.FIT);
            }
            if (unbgbtmp != null && rlbtmp != null) {
                Bitmap bgbtmp = ScalingUtilities.createScaledBitmap(unbgbtmp, w, h, ScalingLogic.FIT);
                Bitmap newscaledBitmap = ProcessingBitmapTwo(bgbtmp, rlbtmp);
                unbgbtmp.recycle();
                return getPath(newscaledBitmap);
            }
        }
    }
    return path;

}

From source file:org.appcelerator.titanium.view.TiDrawableReference.java

private int getOrientation() {
    String path = null;//from w w w.java2s  .  c  o m
    int orientation = 0;

    if (isTypeBlob() && blob != null) {
        path = blob.getNativePath();
    } else if (isTypeFile() && file != null) {
        path = file.getNativeFile().getAbsolutePath();
    } else {
        InputStream is = getInputStream();
        if (is != null) {
            File file = TiFileHelper.getInstance().getTempFileFromInputStream(is, "EXIF-TMP", true);
            path = file.getAbsolutePath();
        }
    }

    try {
        if (path == null) {
            Log.e(TAG,
                    "Path of image file could not determined. Could not create an exifInterface from an invalid path.");
            return 0;
        }

        // Remove path prefix
        if (path.startsWith(FILE_PREFIX)) {
            path = path.replaceFirst(FILE_PREFIX, "");
        }

        ExifInterface exifInterface = new ExifInterface(path);
        orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);

        if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
            orientation = 90;
        } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
            orientation = 180;
        } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
            orientation = 270;
        } else {
            orientation = 0;
        }

    } catch (IOException e) {
        Log.e(TAG, "Error creating exifInterface, could not determine orientation.", Log.DEBUG_MODE);
    }

    return orientation;

}

From source file:com.sim2dial.dialer.ChatFragment.java

private void uploadAndSendImage(final String filePath, final Bitmap image, final ImageSize size) {
    uploadLayout.setVisibility(View.VISIBLE);
    textLayout.setVisibility(View.GONE);

    uploadThread = new Thread(new Runnable() {
        @Override//  ww  w  .  j ava  2 s  . c om
        public void run() {
            Bitmap bm = null;
            String url = null;

            if (!uploadThread.isInterrupted()) {
                if (filePath != null) {
                    bm = BitmapFactory.decodeFile(filePath);
                    if (bm != null && size != ImageSize.REAL) {
                        int pixelsMax = size == ImageSize.SMALL ? SIZE_SMALL
                                : size == ImageSize.MEDIUM ? SIZE_MEDIUM : SIZE_LARGE;
                        if (bm.getWidth() > bm.getHeight() && bm.getWidth() > pixelsMax) {
                            bm = Bitmap.createScaledBitmap(bm, pixelsMax,
                                    (pixelsMax * bm.getHeight()) / bm.getWidth(), false);
                        } else if (bm.getHeight() > bm.getWidth() && bm.getHeight() > pixelsMax) {
                            bm = Bitmap.createScaledBitmap(bm, (pixelsMax * bm.getWidth()) / bm.getHeight(),
                                    pixelsMax, false);
                        }
                    }
                } else if (image != null) {
                    bm = image;
                }
            }

            // Rotate the bitmap if possible/needed, using EXIF data
            try {
                if (filePath != null) {
                    ExifInterface exif = new ExifInterface(filePath);
                    int pictureOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
                    Matrix matrix = new Matrix();
                    if (pictureOrientation == 6) {
                        matrix.postRotate(90);
                    } else if (pictureOrientation == 3) {
                        matrix.postRotate(180);
                    } else if (pictureOrientation == 8) {
                        matrix.postRotate(270);
                    }
                    bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            if (bm != null) {
                bm.compress(CompressFormat.JPEG, COMPRESSOR_QUALITY, outStream);
            }

            if (!uploadThread.isInterrupted() && bm != null) {
                url = uploadImage(filePath, bm, COMPRESSOR_QUALITY, outStream.size());
                File file = new File(Environment.getExternalStorageDirectory(),
                        getString(R.string.temp_photo_name));
                file.delete();
            }

            if (!uploadThread.isInterrupted()) {
                final Bitmap fbm = bm;
                final String furl = url;
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        uploadLayout.setVisibility(View.GONE);
                        textLayout.setVisibility(View.VISIBLE);
                        progressBar.setProgress(0);
                        if (furl != null) {
                            sendImageMessage(furl, fbm);
                        } else {
                            Toast.makeText(getActivity(), getString(R.string.error), Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        }
    });
    uploadThread.start();
}

From source file:com.yk.notification.util.BitmapUtil.java

/**
 * ?//from   w w w.  ja v  a2  s .  c  o m
 * 
 * @param path
 *            ?
 * @return 
 */
public static int getImageDegree(String path) {
    int degree = 0;
    try {
        ExifInterface exifInterface = new ExifInterface(path);
        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);
        switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            degree = 90;
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            degree = 180;
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            degree = 270;
            break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return degree;
}

From source file:com.klinker.android.twitter.activities.profile_viewer.ProfilePager.java

private Bitmap getBitmapToSend(Uri uri) throws FileNotFoundException, IOException {
    InputStream input = getContentResolver().openInputStream(uri);

    BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
    onlyBoundsOptions.inJustDecodeBounds = true;
    onlyBoundsOptions.inDither = true;//optional
    onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
    BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
    input.close();/*from w ww.java2s.  co m*/
    if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1))
        return null;

    int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight
            : onlyBoundsOptions.outWidth;

    double ratio = (originalSize > 1000) ? (originalSize / 1000) : 1.0;

    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
    bitmapOptions.inDither = true;//optional
    bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
    input = this.getContentResolver().openInputStream(uri);
    Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);

    ExifInterface exif = new ExifInterface(IOUtils.getPath(uri, context));
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);

    input.close();

    return bitmap;
}

From source file:com.klinker.android.twitter.ui.profile_viewer.ProfilePager.java

private Bitmap getBitmapToSend(Uri uri) throws FileNotFoundException, IOException {
    InputStream input = getContentResolver().openInputStream(uri);

    BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
    onlyBoundsOptions.inJustDecodeBounds = true;
    onlyBoundsOptions.inDither = true;//optional
    onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
    BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
    input.close();//  w  w w .  ja v a2  s . c o m
    if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1))
        return null;

    int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight
            : onlyBoundsOptions.outWidth;

    double ratio = (originalSize > 500) ? (originalSize / 500) : 1.0;

    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
    bitmapOptions.inDither = true;//optional
    bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
    input = this.getContentResolver().openInputStream(uri);
    Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);

    ExifInterface exif = new ExifInterface(IOUtils.getPath(uri, context));
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);

    input.close();

    return rotateBitmap(bitmap, orientation);
}