Example usage for android.media ExifInterface ExifInterface

List of usage examples for android.media ExifInterface ExifInterface

Introduction

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

Prototype

public ExifInterface(InputStream inputStream) throws IOException 

Source Link

Document

Reads Exif tags from the specified image input stream.

Usage

From source file:com.allen.mediautil.ImageTakerHelper.java

/**
 * ?/*from  www  .j  a  v a 2 s .com*/
 *
 * @param path ?
 * @return degree
 */
private static int readPictureDegree(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;// SUPPRESS CHECKSTYLE
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            degree = 180;// SUPPRESS CHECKSTYLE
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            degree = 270;// SUPPRESS CHECKSTYLE
            break;
        default:
            break;
        }
    } catch (IOException e) {
        Log.e("readPictureDegree", "readPictureDegree failed", e);
    }
    return degree;
}

From source file:com.yanzhenjie.album.task.LocalImageLoader.java

/**
 * Read the rotation angle of the picture file.
 *
 * @param path image path./*from w  w w. j  a  va  2  s  . c om*/
 * @return one of 0, 90, 180, 270.
 */
public static int readDegree(String path) {
    try {
        ExifInterface exifInterface = new ExifInterface(path);
        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);
        switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            return 90;
        case ExifInterface.ORIENTATION_ROTATE_180:
            return 180;
        case ExifInterface.ORIENTATION_ROTATE_270:
            return 270;
        default:
            return 0;
        }
    } catch (Exception e) {
        return 0;
    }
}

From source file:com.silentcircle.common.util.ViewUtil.java

/**
 * Finds JPEG image rotation flags from exif and returns matrix to be used to rotate image.
 *
 * @param fileName JPEG image file name.
 *
 * @return Matrix to use in image rotate transformation or null if parsing failed.
 *//*from ww  w.jav a 2  s.  co  m*/
public static Matrix getRotationMatrixFromExif(final String fileName) {
    Matrix matrix = null;
    try {
        ExifInterface exif = new ExifInterface(fileName);
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        int rotate = 0;

        switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            rotate = ROTATE_90;
            break;

        case ExifInterface.ORIENTATION_ROTATE_180:
            rotate = ROTATE_180;
            break;

        case ExifInterface.ORIENTATION_ROTATE_270:
            rotate = ROTATE_270;
            break;
        }

        if (rotate != 0) {
            matrix = new Matrix();
            matrix.preRotate(rotate);
        }
    } catch (IOException e) {
        Log.i(TAG, "Failed to determine image flags from file " + fileName);
    }
    return matrix;
}

From source file:com.google.android.apps.muzei.gallery.GalleryArtSource.java

private void ensureMetadataExists(@NonNull Uri imageUri) {
    Cursor existingMetadata = getContentResolver().query(GalleryContract.MetadataCache.CONTENT_URI,
            new String[] { BaseColumns._ID }, GalleryContract.MetadataCache.COLUMN_NAME_URI + "=?",
            new String[] { imageUri.toString() }, null);
    if (existingMetadata == null) {
        return;/*w w  w.jav a  2s.c om*/
    }
    boolean metadataExists = existingMetadata.moveToFirst();
    existingMetadata.close();
    if (!metadataExists) {
        // No cached metadata or it's stale, need to pull it separately using Exif
        ContentValues values = new ContentValues();
        values.put(GalleryContract.MetadataCache.COLUMN_NAME_URI, imageUri.toString());

        InputStream in = null;
        try {
            ExifInterface exifInterface;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                in = getContentResolver().openInputStream(imageUri);
                exifInterface = new ExifInterface(in);
            } else {
                File imageFile = GalleryProvider.getLocalFileForUri(this, imageUri);
                if (imageFile == null) {
                    return;
                }
                exifInterface = new ExifInterface(imageFile.getPath());
            }
            String dateString = exifInterface.getAttribute(ExifInterface.TAG_DATETIME);
            if (!TextUtils.isEmpty(dateString)) {
                Date date = sExifDateFormat.parse(dateString);
                values.put(GalleryContract.MetadataCache.COLUMN_NAME_DATETIME, date.getTime());
            }

            float[] latlong = new float[2];
            if (exifInterface.getLatLong(latlong)) {
                // Reverse geocode
                List<Address> addresses = mGeocoder.getFromLocation(latlong[0], latlong[1], 1);
                if (addresses != null && addresses.size() > 0) {
                    Address addr = addresses.get(0);
                    String locality = addr.getLocality();
                    String adminArea = addr.getAdminArea();
                    String countryCode = addr.getCountryCode();
                    StringBuilder sb = new StringBuilder();
                    if (!TextUtils.isEmpty(locality)) {
                        sb.append(locality);
                    }
                    if (!TextUtils.isEmpty(adminArea)) {
                        if (sb.length() > 0) {
                            sb.append(", ");
                        }
                        sb.append(adminArea);
                    }
                    if (!TextUtils.isEmpty(countryCode) && !sOmitCountryCodes.contains(countryCode)) {
                        if (sb.length() > 0) {
                            sb.append(", ");
                        }
                        sb.append(countryCode);
                    }
                    values.put(GalleryContract.MetadataCache.COLUMN_NAME_LOCATION, sb.toString());
                }
            }

            getContentResolver().insert(GalleryContract.MetadataCache.CONTENT_URI, values);
        } catch (ParseException e) {
            Log.w(TAG, "Couldn't read image metadata.", e);
        } catch (IOException e) {
            Log.w(TAG, "Couldn't write temporary image file.", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignored) {
                }
            }
        }
    }
}

From source file:com.wallerlab.compcellscope.Image_Gallery.java

private void writeJsonFile(File[] files) throws JSONException {

    ExifInterface inter;//from  ww w .j  a  va 2  s  . co m

    //Can write meta deta to the JSON File
    JSONArray image_files = new JSONArray();
    for (int i = 0; i < files.length; i++) {
        File file = files[i];
        JSONObject image = new JSONObject();
        String one = file.getName().toString();

        Log.d(LOG, "Fileyyyyyy: " + file.getPath());
        //Get Information about picture hidden in tags
        try {
            inter = new ExifInterface(file.getPath());
            Log.d(LOG, "Date Taken: " + inter.getAttribute(ExifInterface.TAG_DATETIME));
            Log.d(LOG, "GPSTimeStamp Taken: " + inter.getAttribute(ExifInterface.TAG_GPS_DATESTAMP));
            Log.d(LOG, "Make Taken: " + inter.getAttribute(ExifInterface.TAG_MAKE));
        } catch (IOException e) {
            e.printStackTrace();
        }

        Integer.parseInt(one.substring(one.lastIndexOf("(") + 1, one.lastIndexOf(")")));
        Integer.parseInt(one.substring(one.lastIndexOf("(") + 1, one.lastIndexOf(")")));
        image.put("name", one);
        image.put("focus", Integer.parseInt(one.substring(one.lastIndexOf("(") + 1, one.lastIndexOf(")"))));

        image_files.put(image);
    }

    try {
        FileWriter file = new FileWriter(files[0].getParent().toString() + File.separator + "info.json");
        file.write("test");
        file.flush();
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.spoiledmilk.ibikecph.util.Util.java

public static Bitmap bmpDecodeFile(File f, int width_limit, int height_limit, long max_size,
        boolean max_dimensions) {
    if (f == null) {
        return null;
    }/* w  w  w .  j  a v  a2  s . com*/

    LOG.d("bmpDecodeFile(" + f.getAbsolutePath() + "," + width_limit + "," + height_limit + "," + max_size + ","
            + max_dimensions + ")");

    Bitmap bmp = null;
    boolean shouldReturn = false;

    FileInputStream fin = null;
    int orientation = ExifInterface.ORIENTATION_NORMAL;
    try {
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        fin = new FileInputStream(f);
        BitmapFactory.decodeStream(fin, null, o);
        try {
            fin.close();
            fin = null;
        } catch (IOException e) {
        }

        // Find the correct scale value. It should be the power of 2.
        int scale = 1;
        if (width_limit != -1 && height_limit != -1) {
            if (max_dimensions) {
                while (o.outWidth / scale > width_limit || o.outHeight / scale > height_limit)
                    scale *= 2;
            } else {
                while (o.outWidth / scale / 2 >= width_limit && o.outHeight / scale / 2 >= height_limit)
                    scale *= 2;
            }
        } else if (max_size != -1)
            while ((o.outWidth * o.outHeight) / (scale * scale) > max_size)
                scale *= 2;

        // Decode with inSampleSize
        o = null;
        if (scale > 1) {
            o = new BitmapFactory.Options();
            o.inSampleSize = scale;
        }
        fin = new FileInputStream(f);
        try {
            bmp = BitmapFactory.decodeStream(fin, null, o);
        } catch (OutOfMemoryError e) {
            // Try to recover from out of memory error - but keep in mind
            // that behavior after this error is
            // undefined,
            // for example more out of memory errors might appear in catch
            // block.
            if (bmp != null)
                bmp.recycle();
            bmp = null;
            System.gc();
            LOG.e("Util.bmpDecodeFile() OutOfMemoryError in decodeStream()! Trying to recover...");
        }

        if (bmp != null) {
            LOG.d("resulting bitmap width : " + bmp.getWidth() + " height : " + bmp.getHeight() + " size : "
                    + (bmp.getRowBytes() * bmp.getHeight()));

            ExifInterface exif = new ExifInterface(f.getPath());
            orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        }
    } catch (FileNotFoundException e) {
        shouldReturn = true;
    } catch (IOException e) {
        shouldReturn = true; // bitmap is still valid here, just can't be
        // rotated
    } finally {
        if (fin != null)
            try {
                fin.close();
            } catch (IOException e) {
            }
    }

    if (shouldReturn || bmp == null)
        return bmp;

    float rotate = 0;
    switch (orientation) {
    case ExifInterface.ORIENTATION_ROTATE_90:
        rotate = 90;
        break;
    case ExifInterface.ORIENTATION_ROTATE_180:
        rotate = 180;
        break;
    case ExifInterface.ORIENTATION_ROTATE_270:
        rotate = 270;
        break;
    }
    if (rotate > 0) {
        Matrix matrix = new Matrix();
        matrix.postRotate(rotate);
        Bitmap bmpRot = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
        matrix = null;
        bmp.recycle();
        bmp = null;
        // System.gc();
        return bmpRot;
    }

    return bmp;
}

From source file:freed.viewer.screenslide.ScreenSlideFragment.java

private void processExif(final File file) {
    FreeDPool.Execute(new Runnable() {
        @Override//from   w  w w  .j  a va  2  s.  com
        public void run() {
            try {
                final ExifInterface exifInterface = new ExifInterface(file.getAbsolutePath());
                iso.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            shutter.setText("S:" + exifInterface.getAttribute(ExifInterface.TAG_EXPOSURE_TIME));
                        } catch (NullPointerException e) {
                            shutter.setVisibility(View.GONE);
                        }
                        try {
                            fnumber.setText("f~:" + exifInterface.getAttribute(ExifInterface.TAG_F_NUMBER));
                        } catch (NullPointerException e) {
                            fnumber.setVisibility(View.GONE);
                        }
                        try {
                            focal.setText("A:" + exifInterface.getAttribute(ExifInterface.TAG_APERTURE_VALUE));
                        } catch (NullPointerException e) {
                            focal.setVisibility(View.GONE);
                        }
                        try {
                            iso.setText(
                                    "ISO:" + exifInterface.getAttribute(ExifInterface.TAG_ISO_SPEED_RATINGS));
                        } catch (NullPointerException e) {
                            iso.setVisibility(View.GONE);
                        }
                    }
                });

            } catch (NullPointerException | IOException ex) {
                Log.d(TAG, "Failed to read Exif");
            }
        }
    });
}

From source file:com.example.photoremark.MainActivity.java

/**
 * ?exif?/*from  w w  w. j a  v a 2s . c  om*/
 *
 * @param path 
 * @return
 */
public int getPictureDegree(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:me.tipi.kiosk.ui.fragments.OCRFragment.java

@Override
public void onMetadataAvailable(Metadata metadata) {
    // This method will be called when metadata becomes available during recognition process.
    // Here, for every metadata type that is allowed through metadata settings,
    // desired actions can be performed.
    // detection metadata contains detection locations
    if (metadata instanceof DetectionMetadata) {
        // detection location is written inside DetectorResult
        DetectorResult detectorResult = ((DetectionMetadata) metadata).getDetectionResult();
        // DetectorResult can be null - this means that detection has failed
        if (detectorResult == null) {
            if (mQvManager != null) {
                // begin quadrilateral animation to its default position
                // (internally displays FAIL status)
                mQvManager.animateQuadToDefaultPosition();
            }//from   ww  w  . ja va 2s .c om
            // when points of interested have been detected (e.g. QR code), this will be returned as PointsDetectorResult
        } else if (detectorResult instanceof QuadDetectorResult) {
            // begin quadrilateral animation to detected quadrilateral
            mQvManager.animateQuadToDetectionPosition((QuadDetectorResult) detectorResult);
        }
    } else if (metadata instanceof ImageMetadata) {
        // obtain image
        // Please note that Image's internal buffers are valid only
        // until this method ends. If you want to save image for later,
        // obtained a cloned image with image.clone().

        if (guest.passportPath == null || TextUtils.isEmpty(guest.passportPath) || this.results == null) {
            Image image = ((ImageMetadata) metadata).getImage();

            if (image != null && image.getImageType() == ImageType.SUCCESSFUL_SCAN) {
                Timber.w("Metadata type is successful frame image, we go to save it");
                image.clone();
                Timber.w("Ocr meta data captured");
                final Bitmap bitmap = image.convertToBitmap();
                Timber.w("Metadata converted to bitmap");
                final Uri photoUri = ImageUtility.savePassportPicture(getActivity(), bitmap);
                Timber.w("OCR Uri got back from file helper with path: %s",
                        photoUri != null ? photoUri.getPath() : "NO OCR FILE PATH!!!!!");
                ExifInterface ei = null;
                try {
                    ei = new ExifInterface(photoUri.getPath());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                int orientation = ei != null
                        ? ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)
                        : 0;
                Timber.w("Ocr image orientation angle is: %d", orientation);

                Bitmap rotated = null;

                switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    rotated = rotateImage(bitmap, 90);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    rotated = rotateImage(bitmap, 180);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    rotated = rotateImage(bitmap, 270);
                    break;
                case ExifInterface.ORIENTATION_UNDEFINED:
                    rotated = rotateImage(bitmap, 90);
                    break;
                case ExifInterface.ORIENTATION_NORMAL:
                default:
                    break;
                }

                final Uri rotatedUri = ImageUtility.savePassportPicture(getActivity(), rotated);
                Timber.w("OCR ROTATED Uri got back from file helper with path: %s",
                        rotatedUri != null ? rotatedUri.getPath() : "NO OCR FILE PATH!!!!!");
                guest.passportPath = rotatedUri.getPath();
                Timber.w("Ocr path saved with path: %s", rotatedUri.getPath());
            }
        } else {
            Timber.w("We have ocr path and it's : %s", guest.passportPath);
        }
        // to convert the image to Bitmap, call image.convertToBitmap()

        // after this line, image gets disposed. If you want to save it
        // for later, you need to clone it with image.clone()
    }
}

From source file:org.linphone.ContactEditorFragment.java

private void editContactPicture(final String filePath, final Bitmap image) {
    int SIZE_SMALL = 256;
    int COMPRESSOR_QUALITY = 100;
    Bitmap bitmapUnknown = BitmapFactory.decodeResource(getResources(), R.drawable.avatar);
    Bitmap bm = null;//  w ww. j a  v a 2  s.  c o m

    if (filePath != null) {
        int pixelsMax = SIZE_SMALL;
        //Resize image
        bm = BitmapFactory.decodeFile(filePath);
        if (bm != null) {
            if (bm.getWidth() > bm.getHeight() && bm.getWidth() > pixelsMax) {
                bm = Bitmap.createScaledBitmap(bm, 256, 256, false);
            }
        }
    } else if (image != null) {
        bm = image;
    }

    // Rotate the bitmap if possible/needed, using EXIF data
    try {
        if (imageToUploadUri != null && 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();
    }

    Bitmap bitmapRounded;
    if (bm != null) {
        bitmapRounded = Bitmap.createScaledBitmap(bm, bitmapUnknown.getWidth(), bitmapUnknown.getWidth(),
                false);

        Canvas canvas = new Canvas(bitmapRounded);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setShader(new BitmapShader(bitmapRounded, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
        canvas.drawCircle(bitmapRounded.getWidth() / 2 + 0.7f, bitmapRounded.getHeight() / 2 + 0.7f,
                bitmapRounded.getWidth() / 2 + 0.1f, paint);
        contactPicture.setImageBitmap(bitmapRounded);

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, COMPRESSOR_QUALITY, outStream);
        photoToAdd = outStream.toByteArray();
    }
}