Example usage for org.apache.cordova FileUtils getMimeType

List of usage examples for org.apache.cordova FileUtils getMimeType

Introduction

In this page you can find the example usage for org.apache.cordova FileUtils getMimeType.

Prototype

public static String getMimeType(String filename) 

Source Link

Document

Looks up the mime type of a given file name.

Usage

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

License:Apache License

/**
 * Called when the camera view exits./*from  w ww.j av a  2s.  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.phonegap.plugins.wsiCapture.WsiCapture.java

License:Apache License

/**
 * Provides the media data file data depending on it's mime type
 * /*w ww.  java  2 s .  c o  m*/
 * @param filePath
 *            path to the file
 * @param mimeType
 *            of the file
 * @return a MediaFileData object
 */
private JSONObject getFormatData(String filePath, String mimeType) throws JSONException {
    JSONObject obj = new JSONObject();
    // setup defaults
    obj.put("height", 0);
    obj.put("width", 0);
    obj.put("bitrate", 0);
    obj.put("duration", 0);
    obj.put("codecs", "");

    // If the mimeType isn't set the rest will fail
    // so let's see if we can determine it.
    if (mimeType == null || mimeType.equals("") || "null".equals(mimeType)) {
        mimeType = FileUtils.getMimeType(filePath);
    }
    //Log.d(LOG_TAG, "Mime type = " + mimeType);

    if (mimeType.equals(IMAGE_JPEG) || filePath.endsWith(".jpg")) {
        obj = getImageData(filePath, obj);
    } else if (mimeType.endsWith(AUDIO_3GPP)) {
        obj = getAudioVideoData(filePath, obj, false);
    } else if (mimeType.equals(VIDEO_3GPP) || mimeType.equals(VIDEO_MP4)) {
        obj = getAudioVideoData(filePath, obj, true);
    }
    return obj;
}

From source file:com.phonegap.plugins.wsiCapture.WsiCapture.java

License:Apache License

/**
 * Creates a JSONObject that represents a File from the Uri
 * /* w  w  w .  j a v  a  2 s .  co  m*/
 * @param data
 *            the Uri of the audio/image/video
 * @return a JSONObject that represents a File
 * @throws IOException
 */
private JSONObject createMediaFile(Uri data) {
    File fp = new File(this.getRealPathFromURI(data, this.cordova));
    JSONObject obj = new JSONObject();

    try {
        // File properties
        obj.put("name", fp.getName());
        obj.put("fullPath", "file://" + fp.getAbsolutePath());
        // Because of an issue with MimeTypeMap.getMimeTypeFromExtension()
        // all .3gpp files
        // are reported as video/3gpp. I'm doing this hacky check of the URI
        // to see if it
        // is stored in the audio or video content store.
        if (fp.getAbsoluteFile().toString().endsWith(".3gp")
                || fp.getAbsoluteFile().toString().endsWith(".3gpp")) {
            if (data.toString().contains("/audio/")) {
                obj.put("type", AUDIO_3GPP);
            } else {
                obj.put("type", VIDEO_3GPP);
            }
        } else {
            obj.put("type", FileUtils.getMimeType(fp.getAbsolutePath()));
        }

        obj.put("lastModifiedDate", fp.lastModified());
        obj.put("size", fp.length());
    } catch (JSONException e) {
        // this will never happen
        e.printStackTrace();
    }

    return obj;
}