Example usage for android.net Uri getPath

List of usage examples for android.net Uri getPath

Introduction

In this page you can find the example usage for android.net Uri getPath.

Prototype

@Nullable
public abstract String getPath();

Source Link

Document

Gets the decoded path.

Usage

From source file:com.logilite.vision.camera.CameraLauncher.java

/**
 * Applies all needed transformation to the image received from the camera.
 *
 * @param destType          In which form should we return the image
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 *//* w w w  .j a v  a2  s  . c o m*/
private void processResultFromCamera(int destType, Intent intent) throws IOException {
    int rotate = 0;

    // Create an ExifHelper to save the exif data that is lost during compression
    ExifHelper exif = new ExifHelper();
    try {
        if (this.encodingType == JPEG) {
            exif.createInFile(getTempDirectoryPath() + "/.Pic.jpg");
            exif.readExifData();
            rotate = exif.getOrientation();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    Bitmap bitmap = null;
    Uri uri = null;

    // If sending base64 image back
    if (destType == DATA_URL) {
        bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));
        if (bitmap == null) {
            // Try to get the bitmap from intent.
            bitmap = (Bitmap) intent.getExtras().get("data");
        }

        // Double-check the bitmap.
        if (bitmap == null) {
            Log.d(LOG_TAG, "I either have a null image path or bitmap");
            this.failPicture("Unable to create bitmap!");
            return;
        }

        if (rotate != 0 && this.correctOrientation) {
            bitmap = getRotatedBitmap(rotate, bitmap, exif);
        }

        this.processPicture(bitmap);
        checkForDuplicateImage(DATA_URL);
    }

    // If sending filename back
    else if (destType == FILE_URI || destType == NATIVE_URI) {
        if (this.saveToPhotoAlbum) {
            Uri inputUri = getUriFromMediaStore();
            //Just because we have a media URI doesn't mean we have a real file, we need to make it
            uri = Uri.fromFile(new File(FileHelper.getRealPath(inputUri, this.cordova)));
        } else {
            uri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
        }

        if (uri == null) {
            this.failPicture("Error capturing image - no media storage found.");
        }

        // If all this is true we shouldn't compress the image.
        if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                && !this.correctOrientation) {
            writeUncompressedImage(uri);

            this.callbackContext.success(uri.toString());
        } else {
            bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));

            if (rotate != 0 && this.correctOrientation) {
                bitmap = getRotatedBitmap(rotate, bitmap, exif);
            }

            // Add compressed version of captured image to returned media store Uri
            OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
            os.close();

            // Restore exif data to file
            if (this.encodingType == JPEG) {
                String exifPath;
                if (this.saveToPhotoAlbum) {
                    exifPath = FileHelper.getRealPath(uri, this.cordova);
                } else {
                    exifPath = uri.getPath();
                }
                exif.createOutFile(exifPath);
                exif.writeExifData();
            }

        }
        // Send Uri back to JavaScript for viewing image
        this.callbackContext.success(uri.toString());
    }

    this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
    bitmap = null;
}

From source file:com.colorchen.qbase.utils.FileUtil.java

@TargetApi(19)
public static String getPathFromUri(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }/*from w w  w.ja v  a2  s.com*/

        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return "";
}

From source file:com.MustacheMonitor.MustacheMonitor.StacheCam.java

/**
 * Called when the camera view exits./*from   www. j  av  a 2s.  c  o 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;

    // If CAMERA
    if (srcType == CAMERA) {
        // If image available
        if (resultCode == Activity.RESULT_OK) {
            try {
                // Create an ExifHelper to save the exif data that is lost during compression
                ExifHelper exif = new ExifHelper();
                try {
                    if (this.encodingType == JPEG) {
                        exif.createInFile(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity())
                                + "/.Pic.jpg");
                        exif.readExifData();
                        rotate = exif.getOrientation();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Bitmap bitmap = null;
                Uri uri = null;

                // If sending base64 image back
                if (destType == DATA_URL) {
                    bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                    if (rotate != 0 && this.correctOrientation) {
                        bitmap = getRotatedBitmap(rotate, bitmap, exif);
                    }

                    this.processPicture(bitmap);
                    checkForDuplicateImage(DATA_URL);
                }

                // If sending filename back
                else if (destType == FILE_URI) {
                    if (!this.saveToPhotoAlbum) {
                        uri = Uri.fromFile(
                                new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()),
                                        System.currentTimeMillis() + ".jpg"));
                    } else {
                        uri = getUriFromMediaStore();
                    }

                    if (uri == null) {
                        this.failPicture("Error capturing image - no media storage found.");
                    }

                    // If all this is true we shouldn't compress the image.
                    if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                            && rotate == 0) {
                        writeUncompressedImage(uri);

                        this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                    } else {
                        bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                        if (rotate != 0 && this.correctOrientation) {
                            bitmap = getRotatedBitmap(rotate, bitmap, exif);
                        }

                        // Add compressed version of captured image to returned media store Uri
                        OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                        os.close();

                        // Restore exif data to file
                        if (this.encodingType == JPEG) {
                            String exifPath;
                            if (this.saveToPhotoAlbum) {
                                exifPath = FileUtils.getRealPathFromURI(uri, this.cordova);
                            } else {
                                exifPath = uri.getPath();
                            }
                            exif.createOutFile(exifPath);
                            exif.writeExifData();
                        }

                    }
                    // Send Uri back to JavaScript for viewing image
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                }

                this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
                bitmap = null;

            } catch (IOException e) {
                e.printStackTrace();
                this.failPicture("Error capturing image.");
            }
        }

        // If cancelled
        else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Camera cancelled.");
        }

        // If something else
        else {
            this.failPicture("Did not complete!");
        }
    }

    // If retrieving photo from library
    else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = intent.getData();

            // 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) {
                this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
            } else {
                // This is a special case to just return the path as no scaling,
                // rotating or compression needs to be done
                if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                        && destType == FILE_URI && !this.correctOrientation) {
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                } else {
                    // Get the path to the image. Makes loading so much easier.
                    String imagePath = FileUtils.getRealPathFromURI(uri, this.cordova);
                    Log.d(LOG_TAG, "Real path = " + imagePath);
                    // If we don't have a valid image so quit.
                    if (imagePath == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to retreive path to picture!");
                        return;
                    }
                    Bitmap bitmap = getScaledBitmap(imagePath);
                    if (bitmap == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to create bitmap!");
                        return;
                    }

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

                    // If sending base64 image back
                    if (destType == DATA_URL) {
                        this.processPicture(bitmap);
                    }

                    // If sending filename back
                    else if (destType == FILE_URI) {
                        // Do we need to scale the returned file
                        if (this.targetHeight > 0 && this.targetWidth > 0) {
                            try {
                                // Create an ExifHelper to save the exif data that is lost during compression
                                String resizePath = DirectoryManager
                                        .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(FileUtils.getRealPathFromURI(uri, this.cordova));
                                    exif.writeExifData();
                                }

                                // The resized image is cached by the app in order to get around this and not have to delete you
                                // application cache I'm adding the current system time to the end of the file url.
                                this.success(
                                        new PluginResult(PluginResult.Status.OK,
                                                ("file://" + resizePath + "?" + System.currentTimeMillis())),
                                        this.callbackId);
                            } catch (Exception e) {
                                e.printStackTrace();
                                this.failPicture("Error retrieving image.");
                            }
                        } else {
                            this.success(new PluginResult(PluginResult.Status.OK, uri.toString()),
                                    this.callbackId);
                        }
                    }
                    if (bitmap != null) {
                        bitmap.recycle();
                        bitmap = null;
                    }
                    System.gc();
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Selection cancelled.");
        } else {
            this.failPicture("Selection did not complete!");
        }
    }
}

From source file:cgeo.geocaching.CacheDetailActivity.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState, R.layout.cachedetail_activity);

    // get parameters
    final Bundle extras = getIntent().getExtras();
    final Uri uri = AndroidBeam.getUri(getIntent());

    // try to get data from extras
    String name = null;//w  ww. j  a v  a2  s.c  o m
    String guid = null;

    if (extras != null) {
        geocode = extras.getString(Intents.EXTRA_GEOCODE);
        name = extras.getString(Intents.EXTRA_NAME);
        guid = extras.getString(Intents.EXTRA_GUID);
    }

    // When clicking a cache in MapsWithMe, we get back a PendingIntent
    if (StringUtils.isEmpty(geocode)) {
        geocode = MapsMeCacheListApp.getCacheFromMapsWithMe(this, getIntent());
    }

    if (geocode == null && uri != null) {
        geocode = ConnectorFactory.getGeocodeFromURL(uri.toString());
    }

    // try to get data from URI
    if (geocode == null && guid == null && uri != null) {
        final String uriHost = uri.getHost().toLowerCase(Locale.US);
        final String uriPath = uri.getPath().toLowerCase(Locale.US);
        final String uriQuery = uri.getQuery();

        if (uriQuery != null) {
            Log.i("Opening URI: " + uriHost + uriPath + "?" + uriQuery);
        } else {
            Log.i("Opening URI: " + uriHost + uriPath);
        }

        if (uriHost.contains("geocaching.com")) {
            if (StringUtils.startsWith(uriPath, "/geocache/gc")) {
                geocode = StringUtils.substringBefore(uriPath.substring(10), "_").toUpperCase(Locale.US);
            } else {
                geocode = uri.getQueryParameter("wp");
                guid = uri.getQueryParameter("guid");

                if (StringUtils.isNotBlank(geocode)) {
                    geocode = geocode.toUpperCase(Locale.US);
                    guid = null;
                } else if (StringUtils.isNotBlank(guid)) {
                    geocode = null;
                    guid = guid.toLowerCase(Locale.US);
                } else {
                    showToast(res.getString(R.string.err_detail_open));
                    finish();
                    return;
                }
            }
        }
    }

    // no given data
    if (geocode == null && guid == null) {
        showToast(res.getString(R.string.err_detail_cache));
        finish();
        return;
    }

    // If we open this cache from a search, let's properly initialize the title bar, even if we don't have cache details
    setCacheTitleBar(geocode, name, null);

    final LoadCacheHandler loadCacheHandler = new LoadCacheHandler(this, progress);

    try {
        String title = res.getString(R.string.cache);
        if (StringUtils.isNotBlank(name)) {
            title = name;
        } else if (geocode != null && StringUtils.isNotBlank(geocode)) { // can't be null, but the compiler doesn't understand StringUtils.isNotBlank()
            title = geocode;
        }
        progress.show(this, title, res.getString(R.string.cache_dialog_loading_details), true,
                loadCacheHandler.disposeMessage());
    } catch (final RuntimeException ignored) {
        // nothing, we lost the window
    }

    final int pageToOpen = savedInstanceState != null ? savedInstanceState.getInt(STATE_PAGE_INDEX, 0)
            : Settings.isOpenLastDetailsPage() ? Settings.getLastDetailsPage() : 1;
    createViewPager(pageToOpen, new OnPageSelectedListener() {

        @Override
        public void onPageSelected(final int position) {
            if (Settings.isOpenLastDetailsPage()) {
                Settings.setLastDetailsPage(position);
            }
            // lazy loading of cache images
            if (getPage(position) == Page.IMAGES) {
                loadCacheImages();
            }
            requireGeodata = getPage(position) == Page.DETAILS;
            startOrStopGeoDataListener(false);

            // dispose contextual actions on page change
            if (currentActionMode != null) {
                currentActionMode.finish();
            }
        }
    });
    requireGeodata = pageToOpen == 1;

    final String realGeocode = geocode;
    final String realGuid = guid;
    AndroidRxUtils.networkScheduler.scheduleDirect(new Runnable() {
        @Override
        public void run() {
            search = Geocache.searchByGeocode(realGeocode, StringUtils.isBlank(realGeocode) ? realGuid : null,
                    false, loadCacheHandler);
            loadCacheHandler.sendMessage(Message.obtain());
        }
    });

    // Load Generic Trackables
    if (StringUtils.isNotBlank(geocode)) {
        AndroidRxUtils.bindActivity(this,
                // Obtain the active connectors and load trackables in parallel.
                Observable.fromIterable(ConnectorFactory.getGenericTrackablesConnectors())
                        .flatMap(new Function<TrackableConnector, Observable<Trackable>>() {
                            @Override
                            public Observable<Trackable> apply(final TrackableConnector trackableConnector) {
                                processedBrands.add(trackableConnector.getBrand());
                                return Observable.defer(new Callable<Observable<Trackable>>() {
                                    @Override
                                    public Observable<Trackable> call() {
                                        return Observable
                                                .fromIterable(trackableConnector.searchTrackables(geocode));
                                    }
                                }).subscribeOn(AndroidRxUtils.networkScheduler);
                            }
                        }).toList())
                .subscribe(new Consumer<List<Trackable>>() {
                    @Override
                    public void accept(final List<Trackable> trackables) {
                        // Todo: this is not really a good method, it may lead to duplicates ; ie: in OC connectors.
                        // Store trackables.
                        genericTrackables.addAll(trackables);
                        if (!trackables.isEmpty()) {
                            // Update the UI if any trackables were found.
                            notifyDataSetChanged();
                        }
                    }
                });
    }

    locationUpdater = new CacheDetailsGeoDirHandler(this);

    // If we have a newer Android device setup Android Beam for easy cache sharing
    AndroidBeam.enable(this, this);
}

From source file:androidx.media.widget.VideoView2.java

private void openVideo(Uri uri, Map<String, String> headers) {
    resetPlayer();/*from  w w w. ja v  a 2 s.co m*/
    if (isRemotePlayback()) {
        // TODO (b/77158231)
        // mRoutePlayer.openVideo(dsd);
        return;
    }

    try {
        Log.d(TAG, "openVideo(): creating new MediaPlayer instance.");
        mMediaPlayer = new MediaPlayer();
        mSurfaceView.setMediaPlayer(mMediaPlayer);
        mTextureView.setMediaPlayer(mMediaPlayer);
        mCurrentView.assignSurfaceToMediaPlayer(mMediaPlayer);

        final Context context = getContext();
        // TODO: Add timely firing logic for more accurate sync between CC and video frame
        // mSubtitleController = new SubtitleController(context);
        // mSubtitleController.registerRenderer(new ClosedCaptionRenderer(context));
        // mSubtitleController.setAnchor((SubtitleController.Anchor) mSubtitleView);

        mMediaPlayer.setOnPreparedListener(mPreparedListener);
        mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
        mMediaPlayer.setOnCompletionListener(mCompletionListener);
        mMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener);
        mMediaPlayer.setOnErrorListener(mErrorListener);
        mMediaPlayer.setOnInfoListener(mInfoListener);
        mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);

        mCurrentBufferPercentage = -1;
        mMediaPlayer.setDataSource(getContext(), uri, headers);
        mMediaPlayer.setAudioAttributes(mAudioAttributes);
        // mMediaPlayer.setOnSubtitleDataListener(mSubtitleListener);
        // we don't set the target state here either, but preserve the
        // target state that was there before.
        mCurrentState = STATE_PREPARING;
        mMediaPlayer.prepareAsync();

        // Save file name as title since the file may not have a title Metadata.
        mTitle = uri.getPath();
        String scheme = uri.getScheme();
        if (scheme != null && scheme.equals("file")) {
            mTitle = uri.getLastPathSegment();
        }
        mRetriever = new MediaMetadataRetriever();
        mRetriever.setDataSource(getContext(), uri);

        if (DEBUG) {
            Log.d(TAG, "openVideo(). mCurrentState=" + mCurrentState + ", mTargetState=" + mTargetState);
        }
    } catch (IOException | IllegalArgumentException ex) {
        Log.w(TAG, "Unable to open content: " + uri, ex);
        mCurrentState = STATE_ERROR;
        mTargetState = STATE_ERROR;
        mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, MediaPlayer.MEDIA_ERROR_IO);
    }
}

From source file:com.runye.express.chat.activity.ChatActivity.java

/**
 * /*w  ww . j a v  a2 s.  com*/
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_CODE_EXIT_GROUP) {
        setResult(RESULT_OK);
        finish();
        return;
    }
    if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
        switch (resultCode) {
        case RESULT_CODE_COPY: // ??
            EMMessage copyMsg = (adapter.getItem(data.getIntExtra("position", -1)));
            if (copyMsg.getType() == EMMessage.Type.IMAGE) {
                ImageMessageBody imageBody = (ImageMessageBody) copyMsg.getBody();
                // ???
                clipboard.setText(COPY_IMAGE + imageBody.getLocalUrl());
            } else {
                // clipboard.setText(SmileUtils.getSmiledText(ChatActivity.this,
                // ((TextMessageBody) copyMsg.getBody()).getMessage()));
                clipboard.setText(((TextMessageBody) copyMsg.getBody()).getMessage());
            }
            break;
        case RESULT_CODE_DELETE: // ?
            EMMessage deleteMsg = adapter.getItem(data.getIntExtra("position", -1));
            conversation.removeMessage(deleteMsg.getMsgId());
            adapter.refresh();
            listView.setSelection(data.getIntExtra("position", adapter.getCount()) - 1);
            break;

        case RESULT_CODE_FORWARD: // ??
            EMMessage forwardMsg = adapter.getItem(data.getIntExtra("position", 0));
            Intent intent = new Intent(this, ForwardMessageActivity.class);
            intent.putExtra("forward_msg_id", forwardMsg.getMsgId());
            startActivity(intent);

            break;

        default:
            break;
        }
    }
    if (resultCode == RESULT_OK) { // ?
        if (requestCode == REQUEST_CODE_EMPTY_HISTORY) {
            // ?
            EMChatManager.getInstance().clearConversation(toChatUsername);
            adapter.refresh();
        } else if (requestCode == REQUEST_CODE_CAMERA) { // ??
            if (cameraFile != null && cameraFile.exists())
                sendPicture(cameraFile.getAbsolutePath());
        } else if (requestCode == REQUEST_CODE_SELECT_VIDEO) {

            Uri videoUri = data.getData();
            String[] proj = { MediaStore.Images.Media.DATA, MediaStore.Video.Media.DURATION };
            try {
                Cursor cursor = getContentResolver().query(videoUri, proj, null, null, null);
                if (cursor != null) {
                    if (cursor.moveToFirst()) {
                        int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        int duration = cursor
                                .getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
                        String videoPath = cursor.getString(index);
                        Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
                        if (bitmap == null) {
                            EMLog.d("chatactivity", "problem load video thumbnail bitmap,use default icon");
                            bitmap = BitmapFactory.decodeResource(getResources(),
                                    R.drawable.chat_app_panel_video_icon);
                        }
                        File videoFile = new File(videoPath);
                        System.out.println("length:" + videoFile.length());
                        // ???5M
                        if (videoFile.length() > 1024 * 1024 * 5) {
                            Toast.makeText(this, "??5M?", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        // get the thumb image file
                        File file = new File(PathUtil.getInstance().getVideoPath(), "th" + videoFile.getName());
                        try {
                            if (!file.getParentFile().exists()) {
                                file.getParentFile().mkdirs();
                            }
                            bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream(file));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        sendVideo(videoPath, file.getAbsolutePath(), duration);
                    }
                } else {
                    File videoFile = new File(videoUri.getPath());
                    Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(videoFile.getAbsolutePath(), 3);
                    if (bitmap == null) {
                        EMLog.d("chatactivity", "problem load video thumbnail bitmap,use default icon");
                        bitmap = BitmapFactory.decodeResource(getResources(),
                                R.drawable.chat_app_panel_video_icon);
                    }

                    System.out.println("length:" + videoFile.length());
                    // ???5M
                    if (videoFile.length() > 1024 * 1024 * 5) {
                        Toast.makeText(this, "??5M?", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    // get the thumb image file
                    File file = new File(PathUtil.getInstance().getVideoPath(), "th" + videoFile.getName());
                    try {
                        if (!file.getParentFile().exists()) {
                            file.getParentFile().mkdirs();
                        }
                        bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream(file));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    sendVideo(videoFile.getAbsolutePath(), file.getAbsolutePath(), 0);

                }

            } catch (Exception e) {
                System.out.println("exception:" + e.getMessage());
            }

        } else if (requestCode == REQUEST_CODE_CAMERA_VIDEO) {
            if (videoFile != null && videoFile.exists()) {
                // ?
                String thumbPath = com.easemob.util.ImageUtils.saveVideoThumb(videoFile, 120, 120,
                        Thumbnails.MINI_KIND);
                sendVideo(videoFile.getAbsolutePath(), thumbPath, 1);
            }
        } else if (requestCode == REQUEST_CODE_LOCAL) { // ??
            if (data != null) {
                Uri selectedImage = data.getData();
                if (selectedImage != null)
                    sendPicByUri(selectedImage);
            }
        } else if (requestCode == REQUEST_CODE_MAP) { // 
            double latitude = data.getDoubleExtra("latitude", 0);
            double longitude = data.getDoubleExtra("longitude", 0);
            String locationAddress = data.getStringExtra("address");
            if (locationAddress != null && !locationAddress.equals("")) {
                more(more);
                sendLocationMsg(latitude, longitude, "", locationAddress);
            } else {
                Toast.makeText(this, "????", 0).show();
            }
            // ???
        } else if (requestCode == REQUEST_CODE_TEXT) {
            resendMessage();
        } else if (requestCode == REQUEST_CODE_VOICE) {
            resendMessage();
        } else if (requestCode == REQUEST_CODE_PICTURE) {
            resendMessage();
        } else if (requestCode == REQUEST_CODE_LOCATION) {
            resendMessage();
        } else if (requestCode == REQUEST_CODE_VIDEO) {
            resendMessage();
        } else if (requestCode == REQUEST_CODE_COPY_AND_PASTE) {
            // 
            if (!TextUtils.isEmpty(clipboard.getText())) {
                String pasteText = clipboard.getText().toString();
                if (pasteText.startsWith(COPY_IMAGE)) {
                    // ??path
                    sendPicture(pasteText.replace(COPY_IMAGE, ""));
                }

            }
        } else if (conversation.getMsgCount() > 0) {
            adapter.refresh();
            setResult(RESULT_OK);
        } else if (requestCode == REQUEST_CODE_GROUP_DETAIL) {
            EMChatManager.getInstance().getConversation(toChatUsername);
            adapter.refresh();
        }
    }
}

From source file:com.remobile.camera.CameraLauncher.java

/**
 * Applies all needed transformation to the image received from the camera.
 *
 * @param destType In which form should we return the image
 * @param intent   An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 *//*www  .j  a v a 2 s.  c om*/
private void processResultFromCamera(int destType, Intent intent) throws IOException {
    int rotate = 0;

    // Create an ExifHelper to save the exif data that is lost during compression
    ExifHelper exif = new ExifHelper();
    String sourcePath;
    try {
        if (allowEdit && croppedUri != null) {
            sourcePath = FileHelper.stripFileProtocol(croppedUri.toString());
        } else {
            sourcePath = getTempDirectoryPath() + "/.Pic.jpg";
        }

        //We don't support PNG, so let's not pretend we do
        exif.createInFile(getTempDirectoryPath() + "/.Pic.jpg");
        exif.readExifData();
        rotate = exif.getOrientation();

    } catch (IOException e) {
        e.printStackTrace();
    }

    Bitmap bitmap = null;
    Uri uri = null;

    // If sending base64 image back
    if (destType == DATA_URL) {
        if (croppedUri != null) {
            bitmap = getScaledBitmap(FileHelper.stripFileProtocol(croppedUri.toString()));
        } else {
            bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));
        }
        if (bitmap == null) {
            // Try to get the bitmap from intent.
            bitmap = (Bitmap) intent.getExtras().get("data");
        }

        // Double-check the bitmap.
        if (bitmap == null) {
            Log.d(LOG_TAG, "I either have a null image path or bitmap");
            this.failPicture("Unable to create bitmap!");
            return;
        }

        if (rotate != 0 && this.correctOrientation) {
            bitmap = getRotatedBitmap(rotate, bitmap, exif);
        }

        this.processPicture(bitmap);
        checkForDuplicateImage(DATA_URL);
    }

    // If sending filename back
    else if (destType == FILE_URI || destType == NATIVE_URI) {
        uri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));

        if (this.saveToPhotoAlbum) {
            //Create a URI on the filesystem so that we can write the file.
            uri = Uri.fromFile(new File(getPicutresPath()));
        } else {
            uri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
        }

        if (uri == null) {
            this.failPicture("Error capturing image - no media storage found.");
            return;
        }

        // If all this is true we shouldn't compress the image.
        if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                && !this.correctOrientation) {
            writeUncompressedImage(uri);

            this.callbackContext.success(uri.toString());
        } else {
            bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));

            if (rotate != 0 && this.correctOrientation) {
                bitmap = getRotatedBitmap(rotate, bitmap, exif);
            }

            // Add compressed version of captured image to returned media store Uri
            OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
            os.close();

            // Restore exif data to file
            if (this.encodingType == JPEG) {
                String exifPath;
                exifPath = uri.getPath();
                exif.createOutFile(exifPath);
                exif.writeExifData();
            }

            //Broadcast change to File System on MediaStore
            if (this.saveToPhotoAlbum) {
                refreshGallery(uri);
            }

            // Send Uri back to JavaScript for viewing image
            this.callbackContext.success(uri.toString());

        }
    } else {
        throw new IllegalStateException();
    }

    this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
    bitmap = null;
}

From source file:com.ludoscity.findmybikes.activities.NearbyActivity.java

@Override
public void onStationListFragmentInteraction(final Uri uri) {

    if (uri.getPath().equalsIgnoreCase("/" + StationListFragment.STATION_LIST_ITEM_CLICK_PATH)) {
        if (!isLookingForBike() || mStationMapFragment.getMarkerBVisibleLatLng() != null) {
            //if null, means the station was clicked twice, hence unchecked
            final StationItem clickedStation = getListPagerAdapter()
                    .getHighlightedStationForPage(mTabLayout.getSelectedTabPosition());

            if (isLookingForBike()) {

                if (mStationMapFragment.getMarkerBVisibleLatLng() != null) {

                    LatLng newALatLng = clickedStation.getLocation();
                    getListPagerAdapter().notifyStationAUpdate(newALatLng, mCurrentUserLatLng);

                    mStationMapFragment//from w w w .ja v a2s .  c o m
                            .setMapPaddingRight((int) getResources().getDimension(R.dimen.map_fab_padding));
                    mAutoSelectBikeFab.show();
                    animateCameraToShowUserAndStation(getListPagerAdapter()
                            .getHighlightedStationForPage(StationListPagerAdapter.BIKE_STATIONS));

                    hideSetupShowTripDetailsWidget();
                } else {

                    animateCameraToShowUserAndStation(clickedStation);
                }

                mStationMapFragment.setPinOnStation(true, clickedStation.getId());
                getListPagerAdapter().setupBTabStationARecap(clickedStation, mDataOutdated);
            } else {

                if (mStationMapFragment.isPickedFavoriteMarkerVisible()) {

                    if (clickedStation.getLocation().latitude != mStationMapFragment
                            .getMarkerPickedFavoriteVisibleLatLng().latitude
                            || clickedStation.getLocation().longitude != mStationMapFragment
                                    .getMarkerPickedFavoriteVisibleLatLng().longitude) {
                        mStationMapFragment.pickedFavoriteMarkerInfoWindowShow();
                    } else {
                        mStationMapFragment.pickedFavoriteMarkerInfoWindowHide();
                    }
                }

                setupBTabSelection(clickedStation.getId(), false);

                FavoriteItemStation newFavForStation = new FavoriteItemStation(clickedStation.getId(),
                        clickedStation.getName(), true);

                boolean showFavoriteAddFab = false;

                if (!mStationMapFragment.isPickedFavoriteMarkerVisible()) {
                    if (mStationMapFragment.isPickedPlaceMarkerVisible())
                        showFavoriteAddFab = true; //Don't setup the fab as it's been done in OnActivityResult
                    else if (setupAddFavoriteFab(newFavForStation))
                        showFavoriteAddFab = true;
                }

                if (showFavoriteAddFab)
                    mAddFavoriteFAB.show();
                else
                    mAddFavoriteFAB.hide();
            }
        }
    } else if (uri.getPath()
            .equalsIgnoreCase("/" + StationListFragment.STATION_LIST_INACTIVE_ITEM_CLICK_PATH)) {

        mStationListViewPager.setCurrentItem(StationListPagerAdapter.DOCK_STATIONS, true);
        setupHintMainChoice();
    } else if (uri.getPath().equalsIgnoreCase("/" + StationListFragment.STATION_LIST_FAVORITE_FAB_CLICK_PATH)) {

        StationItem clickedStation = getListPagerAdapter()
                .getHighlightedStationForPage(mTabLayout.getSelectedTabPosition());

        if (null != clickedStation) {

            boolean newState = !clickedStation.isFavorite(this);

            if (newState) {

                if (mOnboardingShowcaseView != null) {
                    mOnboardingShowcaseView.hide();
                    mOnboardingShowcaseView = null;
                }

                if (mStationMapFragment.getMarkerPickedPlaceVisibleName().isEmpty())
                    addFavorite(clickedStation.getFavoriteItemForDisplayName(clickedStation.getName()), false,
                            false);
                else { //there's a third destination
                    addFavorite(clickedStation.getFavoriteItemForDisplayName(
                            mStationMapFragment.getMarkerPickedPlaceVisibleName()), false, false);
                }
                mFavoritesSheetFab.scrollToTop();

            } else {
                removeFavorite(DBHelper.getFavoriteItemForId(this, clickedStation.getId()), false);
            }
        }
    } else if (uri.getPath()
            .equalsIgnoreCase("/" + StationListFragment.STATION_LIST_DIRECTIONS_FAB_CLICK_PATH)) {
        //http://stackoverflow.com/questions/6205827/how-to-open-standard-google-map-application-from-my-application

        final StationItem curSelectedStation = getListPagerAdapter()
                .getHighlightedStationForPage(mTabLayout.getSelectedTabPosition());

        // Seen NullPointerException in crash report.
        if (null != curSelectedStation) {

            LatLng tripLegOrigin = isLookingForBike() ? mCurrentUserLatLng
                    : mStationMapFragment.getMarkerALatLng();
            LatLng tripLegDestination = curSelectedStation.getLocation();
            boolean walkMode = isLookingForBike();

            launchGoogleMapsForDirections(tripLegOrigin, tripLegDestination, walkMode);
        }
    }
}

From source file:io.ingame.squarecamera.CameraLauncher.java

/**
 * Applies all needed transformation to the image received from the camera.
 *
 * @param destType          In which form should we return the image
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 *///from ww w.  j  av a  2  s .  c  o m
private void processResultFromCamera(int destType, Intent intent) throws IOException {
    int rotate = 0;

    // Create an ExifHelper to save the exif data that is lost during compression
    ExifHelper exif = new ExifHelper();
    try {
        if (this.encodingType == JPEG) {
            exif.createInFile(getTempDirectoryPath() + "/.Pic.jpg");
            exif.readExifData();
            rotate = exif.getOrientation();
        } else if (this.encodingType == PNG) {
            exif.createInFile(getTempDirectoryPath() + "/.Pic.png");
            exif.readExifData();
            rotate = exif.getOrientation();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    Bitmap bitmap = null;
    Uri uri = null;

    // If sending base64 image back
    if (destType == DATA_URL) {
        bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));
        if (bitmap == null) {
            // Try to get the bitmap from intent.
            bitmap = (Bitmap) intent.getExtras().get("data");
        }

        // Double-check the bitmap.
        if (bitmap == null) {
            Log.d(LOG_TAG, "I either have a null image path or bitmap");
            this.failPicture("Unable to create bitmap!");
            return;
        }

        if (rotate != 0 && this.correctOrientation) {
            bitmap = getRotatedBitmap(rotate, bitmap, exif);
        }

        this.processPicture(bitmap);
        checkForDuplicateImage(DATA_URL);
    }

    // If sending filename back
    else if (destType == FILE_URI || destType == NATIVE_URI) {
        if (this.saveToPhotoAlbum) {
            Uri inputUri = getUriFromMediaStore();
            try {
                //Just because we have a media URI doesn't mean we have a real file, we need to make it
                uri = Uri.fromFile(new File(FileHelper.getRealPath(inputUri, this.cordova)));
            } catch (NullPointerException e) {
                uri = null;
            }
        } else {
            uri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
        }

        if (uri == null) {
            this.failPicture("Error capturing image - no media storage found.");
            return;
        }

        // If all this is true we shouldn't compress the image.
        if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                && !this.correctOrientation) {
            writeUncompressedImage(uri);

            this.callbackContext.success(uri.toString());
        } else {
            bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));

            if (rotate != 0 && this.correctOrientation) {
                bitmap = getRotatedBitmap(rotate, bitmap, exif);
            }

            // Add compressed version of captured image to returned media store Uri
            OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
            os.close();

            // Restore exif data to file
            if (this.encodingType == JPEG) {
                String exifPath;
                if (this.saveToPhotoAlbum) {
                    exifPath = FileHelper.getRealPath(uri, this.cordova);
                } else {
                    exifPath = uri.getPath();
                }
                exif.createOutFile(exifPath);
                exif.writeExifData();
            }
            if (this.allowEdit) {
                performCrop(uri);
            } else {
                // Send Uri back to JavaScript for viewing image
                this.callbackContext.success(uri.toString());
            }
        }
    } else {
        throw new IllegalStateException();
    }

    this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
    bitmap = null;
}

From source file:de.vanita5.twittnuker.util.Utils.java

public static String getImagePathFromUri(final Context context, final Uri uri) {
    if (context == null || uri == null)
        return null;

    final String mediaUriStart = ParseUtils.parseString(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    if (ParseUtils.parseString(uri).startsWith(mediaUriStart)) {

        final String[] proj = { MediaStore.Images.Media.DATA };
        final Cursor cur = ContentResolverUtils.query(context.getContentResolver(), uri, proj, null, null,
                null);// www.j  av a 2 s .com

        if (cur == null)
            return null;

        final int idxData = cur.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        cur.moveToFirst();
        try {
            return cur.getString(idxData);
        } finally {
            cur.close();
        }
    } else {
        final String path = uri.getPath();
        if (path != null && new File(path).exists())
            return path;
    }
    return null;
}