Example usage for android.graphics BitmapFactory decodeFile

List of usage examples for android.graphics BitmapFactory decodeFile

Introduction

In this page you can find the example usage for android.graphics BitmapFactory decodeFile.

Prototype

public static Bitmap decodeFile(String pathName) 

Source Link

Document

Decode a file path into a bitmap.

Usage

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

public static String getFileNameByUri(Context context, Uri uri) {
    String fileName = "unknown";// default fileName
    Uri filePathUri = uri;//from   www  .  ja v a 2 s .  c  o  m
    if (uri.getScheme().toString().compareTo("content") == 0) {
        ParcelFileDescriptor parcelFileDescriptor;
        String filename = null;
        try {
            FileOutputStream fos = null;
            parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r");
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
            String extr = Environment.getExternalStorageDirectory().toString();
            File mFolder = new File(extr + "/CHURCH");
            if (!mFolder.exists()) {
                mFolder.mkdir();
            } else {
                mFolder.delete();
                mFolder.mkdir();
            }

            String s = "rough.png";

            File f = new File(mFolder.getAbsolutePath(), s);

            filename = f.getAbsolutePath();
            Log.d("f", filename);
            try {
                fos = new FileOutputStream(f);
                image.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {

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

                e.printStackTrace();
            }
            parcelFileDescriptor.close();
            return filename;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else if (uri.getScheme().compareTo("file") == 0) {
        fileName = filePathUri.getPath();
        File fill = new File(fileName);
        if (fill.exists()) {
            Log.d("exitst", "exist");
            ParcelFileDescriptor parcelFileDescriptor;
            String filename = null;
            FileOutputStream fos = null;
            Bitmap image = BitmapFactory.decodeFile(fileName);
            String extr = Environment.getExternalStorageDirectory().toString();
            File mFolder = new File(extr + "/CHURCH");
            if (!mFolder.exists()) {
                mFolder.mkdir();
            } else {
                mFolder.delete();
                mFolder.mkdir();
            }

            String s = "rough.png";

            File f = new File(mFolder.getAbsolutePath(), s);

            filename = f.getAbsolutePath();
            Log.d("f", filename);
            try {
                fos = new FileOutputStream(f);
                image.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {

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

                e.printStackTrace();
            }
        } else {
            Log.d("not file exitst", "not exist");
        }
        Log.d("file", "file");
    } else {
        fileName = filePathUri.getPath();
        Log.d("else", "else");
    }

    return fileName;

}

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;/*from  w ww.  j  a  va2 s.  c  om*/

            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.github.gorbin.asne.facebook.FacebookSocialNetwork.java

private void postPhoto(final String path, final String message) {
    Bitmap image = BitmapFactory.decodeFile(path);
    SharePhoto photo = new SharePhoto.Builder().setBitmap(image).setCaption(message).build();
    SharePhotoContent content = new SharePhotoContent.Builder().addPhoto(photo).build();

    if (ShareDialog.canShow(SharePhotoContent.class)) {
        shareDialog.show(content);/*ww  w  .j a  va 2  s  .c om*/
    } else {
        if (com.facebook.AccessToken.getCurrentAccessToken().getPermissions().contains(PERMISSION)) {
            ShareApi.share(content, new FacebookCallback<Sharer.Result>() {
                @Override
                public void onSuccess(Sharer.Result result) {
                    Log.v("FACEBOOK_TEST", "share api success");
                    publishSuccess(REQUEST_POST_PHOTO, null);
                }

                @Override
                public void onCancel() {
                    Log.v("FACEBOOK_TEST", "share api cancel");
                    publishSuccess(REQUEST_POST_PHOTO, "postRequestPhoto canceled");
                }

                @Override
                public void onError(FacebookException e) {
                    Log.v("FACEBOOK_TEST", "share api error " + e);
                    publishSuccess(REQUEST_POST_PHOTO, e.toString());
                }
            });
        } else {
            LoginManager.getInstance().logInWithPublishPermissions(fragment.getActivity(),
                    Collections.singletonList(PERMISSION)); //Arrays.asList("publish_actions"));
        }
    }
}

From source file:com.xdyou.sanguo.GameSanGuo.java

private void postImageAndMessage() {
    Bitmap image = null;//ww w .j a v a  2  s  . c  om
    if (imageName != null) {
        image = BitmapFactory.decodeFile(imageName);
        System.out.println("go2play -- image " + image);
    }
    //uploadImage(image);
    sendBuildMessage();

    //      Request request = newFaceBookRequest(Session.getActiveSession(),
    //            imageName, message, null, new Callback()
    //            {
    //               @Override
    //               public void onCompleted(Response response)
    //               {
    //                  // need publish_actions permission
    //                  if (response.getError() != null)
    //                  {
    //                     Log.d("sanguo", "go2play fbShareContent || failed! error=" + response.getError().getErrorMessage());
    //                     runFbShareTips(SHARE_FAILED_INFO);
    //                  }
    //                  else
    //                  {
    //                     Log.d("sanguo", "go2play fbShareContent || succeeded!");
    //                     // ???
    //                     // runFbShareTips(SHARE_SUCCESS_INFO);
    //                     // ???????
    //                     runSendPostSuccess();
    //                  }
    //               }
    //            });
    //      RequestAsyncTask task = new RequestAsyncTask(request);
    //      task.execute();
}

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/*from w ww .j a v  a  2 s . c  o m*/
        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.vendsy.bartsy.venue.BartsyApplication.java

Bitmap loadVenueProfileImage() {
    String file = getFilesDir() + File.separator
            + getResources().getString(R.string.config_venue_profile_picture);
    Log.w(TAG, ">>> Loading venue profile from " + file);
    Bitmap image = null;/*from  w w w  . j a v a 2 s  . c  om*/
    try {
        image = BitmapFactory.decodeFile(file);
    } catch (Exception e) {
        e.printStackTrace();
        Log.d(TAG, "Could not load venue profile image");
    }
    return image;
}

From source file:com.xdyou.sanguo.GameSanGuo.java

public Request newFaceBookRequest(Session session, String imageName, String message, GraphPlace graphPlace,
        Callback callback) {/* w  ww. j a  va 2s  .  c o m*/
    // ?
    if (session != null && session.isOpened()) {
        System.out.println(
                "go2play -- session = " + session.toString() + "session.isOpened : " + session.isOpened());
        Bitmap image = null;
        if (imageName != null) {
            image = BitmapFactory.decodeFile(imageName);
            System.out.println("go2play -- image " + image);
        }

        Bundle parameters = new Bundle();
        // ??
        if (graphPlace != null) {
            parameters.putString("place", graphPlace.getId());
        }
        // ?
        if (message != null) {
            parameters.putString("message", message);
        }
        // ?
        if (image != null) {
            parameters.putParcelable("picture", image);
            // ?
            return new Request(session, "me/photos", parameters, HttpMethod.POST, callback);
        }
        // ???
        return new Request(session, "me/feed", parameters, HttpMethod.POST, callback);
    } else {
        System.out.println("session is null or session is closed!");
        return null;
    }
}

From source file:com.mobicage.rogerthat.plugins.messaging.BrandingMgr.java

protected void dequeue(final BrandedItem item, final boolean failed) {
    synchronized (mLock) {
        if (item.status == BrandedItem.STATUS_DELETED) {
            deleteItemFromQueue(item, false);
            return;
        }//from  ww  w.  jav a  2 s  .  com

        if (failed) {
            item.attemptsLeft -= 1;
            if (item.attemptsLeft > 0) {
                item.status = BrandedItem.STATUS_TODO;
                deleteItemFromQueue(item, false);
                queue(item);
                return;
            }
        }

        item.status = BrandedItem.STATUS_DONE;
        save();
    }

    if (item.type == BrandedItem.TYPE_MESSAGE) {
        final MessageTO message = (MessageTO) item.object;
        mMainService.postOnBIZZHandler(new SafeRunnable() {
            @Override
            protected void safeRun() throws Exception {
                synchronized (mLock) {
                    T.BIZZ();
                    if (item.status == BrandedItem.STATUS_DELETED) {
                        return;
                    }
                    final MessagingPlugin plugin = mMainService.getPlugin(MessagingPlugin.class);
                    plugin.newMessage(message, true, true);

                    item.status = BrandedItem.STATUS_PROCESSING_CALLS;

                    for (int i = 0; i < item.calls.size(); i++) {
                        try {
                            CallReceiver.processCall(item.calls.get(i));
                        } catch (Exception e) {
                            L.bug(e);
                        }
                    }

                    deleteItemFromQueue(item);
                }
            }
        });
    } else if (item.type == BrandedItem.TYPE_JS_EMBEDDING_PACKET) {
        mMainService.postOnBIZZHandler(new SafeRunnable() {
            @Override
            protected void safeRun() throws Exception {
                synchronized (mLock) {
                    T.BIZZ();
                    final JSEmbeddingItemTO packet = (JSEmbeddingItemTO) item.object;
                    deleteItemFromQueue(item);
                    if (!failed) {
                        try {
                            extractJSEmbedding(packet);
                            SystemPlugin systemPlugin = mMainService.getPlugin(SystemPlugin.class);
                            systemPlugin.updateJSEmbeddedPacket(packet.name, packet.hash,
                                    JSEmbedding.STATUS_AVAILABLE);

                            Intent intent = new Intent(JS_EMBEDDING_AVAILABLE_INTENT);
                            intent.putExtra(JS_EMBEDDING_NAME, attachmentDownloadUrlHash(packet.name));
                            mMainService.sendBroadcast(intent);
                        } catch (Exception e) {
                            L.bug("Could not unpack JS Embedding packet", e);
                        }
                    }

                    cleanupJSEmbeddingTmpDownloadFile(packet.name);
                }
            }
        });

    } else if (item.type == BrandedItem.TYPE_LOCAL_FLOW_ATTACHMENT
            || item.type == BrandedItem.TYPE_LOCAL_FLOW_BRANDING) {
        mMainService.postOnBIZZHandler(new SafeRunnable() {
            @Override
            protected void safeRun() throws Exception {
                T.BIZZ();
                synchronized (mLock) {
                    final StartFlowRequest flow = (StartFlowRequest) item.object;
                    deleteItemFromQueue(item);
                    validateStartFlowReady(item, flow);
                }
            }
        });

    } else if (item.type == BrandedItem.TYPE_ATTACHMENT) {
        final AttachmentDownload attachment = (AttachmentDownload) item.object;
        mMainService.postOnBIZZHandler(new SafeRunnable() {
            @Override
            protected void safeRun() throws Exception {
                synchronized (mLock) {
                    T.BIZZ();
                    if (item.status == BrandedItem.STATUS_DELETED) {
                        return;
                    }

                    if (attachment.content_type.toLowerCase(Locale.US).startsWith("image/")) {
                        try {
                            // Make sure the image orientation is correct
                            final File attachmentFile = getAttachmentFile(attachment);
                            final String attachmentPath = attachmentFile.getPath();
                            final int exifRotation = CropUtil.getExifRotation(attachmentPath);
                            Bitmap bm = BitmapFactory.decodeFile(attachmentPath);
                            bm = ImageHelper.rotateBitmap(bm, exifRotation);
                            if (bm != null) {
                                final File tmpFile = new File(attachmentPath + ".tmp");
                                final FileOutputStream stream = new FileOutputStream(tmpFile);
                                try {
                                    bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
                                } finally {
                                    stream.close();
                                }
                                tmpFile.renameTo(attachmentFile);
                            }

                        } catch (Exception e) {
                            L.bug("Failed to rotate the attachment.", e);
                        }
                    }

                    try {
                        final MessagingPlugin messagingPlugin = mMainService.getPlugin(MessagingPlugin.class);
                        messagingPlugin.createAttachmentThumbnail(attachment);
                    } catch (Exception e) {
                        L.bug("Failed to generate attachment thumbnail", e);
                    }

                    Intent intent = new Intent(ATTACHMENT_AVAILABLE_INTENT);
                    intent.putExtra(THREAD_KEY, attachment.threadKey);
                    intent.putExtra(MESSAGE_KEY, attachment.messageKey);
                    intent.putExtra(ATTACHMENT_URL_HASH, attachmentDownloadUrlHash(attachment.download_url));
                    mMainService.sendBroadcast(intent);

                    deleteItemFromQueue(item);
                }
            }

        });
    } else {
        boolean brandingAvailable = false;
        try {
            brandingAvailable = isBrandingAvailable(item.brandingKey);
        } catch (BrandingFailureException e) {
            // Assume not available
        }
        deleteItemFromQueue(item);
        if (brandingAvailable) {
            if (item.type == BrandedItem.TYPE_FRIEND) {
                FriendTO friend = (FriendTO) item.object;
                // Caution: this Friend object only has an email property populated
                Intent intent = new Intent(SERVICE_BRANDING_AVAILABLE_INTENT);
                intent.putExtra(SERVICE_EMAIL, friend.email);
                intent.putExtra(BRANDING_KEY, item.brandingKey);
                mMainService.sendBroadcast(intent);

            } else if (item.type == BrandedItem.TYPE_GENERIC) {
                Intent intent = new Intent(GENERIC_BRANDING_AVAILABLE_INTENT);
                if (item.object != null && item.object instanceof FriendTO) {
                    intent.putExtra(SERVICE_EMAIL, ((FriendTO) item.object).email);
                }
                intent.putExtra(BRANDING_KEY, item.brandingKey);
                mMainService.sendBroadcast(intent);
            }
        }
    }
}

From source file:com.stikyhive.stikyhive.ChattingActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.i(TAG, " ON ACTivyiy result");
    super.onActivityResult(requestCode, resultCode, data);
    Log.i("Result code ", " ^^ " + requestCode);
    if (requestCode == FILE_SELECT_CODE && resultCode == RESULT_OK) {
        Log.i(TAG, " ON ACTivyiy result ^^ 2");
        // Get the Uri of the selected file
        Uri uri = data.getData();//from  ww w .j  a  v a2 s.c o  m
        Log.d("TAG", "File Uri: " + uri.toString());
        // Get the path
        String path;
        try {
            calcualteTodayDate();
            path = getPath(this, uri);
            documentFile = new File(path);

            String extension = "";
            int index = documentFile.getName().lastIndexOf(".");
            if (index != -1) {
                extension = documentFile.getName().substring(index + 1);
            }
            Bitmap bmImg = BitmapFactory.decodeFile(path);
            //   Bitmap resBm = getResizedBitmap(bmImg, 500);
            adapter.add(new StikyChat("", "<img", false, timeSend, "file" + path, 0, 0, "", "", "", null,
                    documentFile.getPath()));
            adapter.notifyDataSetChanged();
            lv.setSelection(adapter.getCount() - 1);
            Log.i("Document File ", " %%%% " + documentFile.getAbsolutePath());
            upLoadServerUri = getApplicationContext().getResources().getString(R.string.url)
                    + "/androidstikyhive/filetransfer.php?fromStikyBee=" + pref.getString("stkid", "")
                    + "&toStikyBee=" + recipientStkid + "&message=photo" + "&extension=" + extension
                    + "&type=file" + "&dateTime=" + URLEncoder.encode(timeSendServer) + "&url="
                    + URLEncoder.encode(getResources().getString(R.string.url));
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    int serverResponseCode = uploadFile(documentFile);
                    if (serverResponseCode == 200) {
                        Log.i("Success", " is done! ");
                        flagChatting = false;
                        flagTransfer = true;
                        messageServer = "<img";
                        msg = "File transfer.";
                        recipientStkidGCM = recipientStkid;
                        new regTask().execute("GCM");
                        new regTask2().execute("Last Message!");
                    }
                }
            }).start();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else if (resultCode == Activity.RESULT_OK && requestCode == GALLERY_ACTIVITY_CODE) {
        Log.i(TAG, " Gallery is clicked..");
        calcualteTodayDate();
        imagePath = data.getStringExtra("picturePath");
        SDFile1 = new File(imagePath);

        String extension = "";
        int index = SDFile1.getName().lastIndexOf(".");
        if (index != -1) {
            extension = SDFile1.getName().substring(index + 1);
        }
        Bitmap bmImg = BitmapFactory.decodeFile(imagePath);
        Bitmap resBm = getResizedBitmap(bmImg, 500);
        adapter.add(new StikyChat("", "<img", false, timeSend, "bitmap" + imagePath, 0, 0, "", "", "", resBm,
                SDFile1.getPath()));
        adapter.notifyDataSetChanged();
        lv.setSelection(adapter.getCount() - 1);
        Log.i("SDFile ", " $$$ " + SDFile1.getAbsolutePath());
        upLoadServerUri = getApplicationContext().getResources().getString(R.string.url)
                + "/androidstikyhive/filetransfer.php?fromStikyBee=" + pref.getString("stkid", "")
                + "&toStikyBee=" + recipientStkid + "&message=photo" + "&extension=" + extension + "&type=image"
                + "&dateTime=" + URLEncoder.encode(timeSendServer) + "&url="
                + URLEncoder.encode(getResources().getString(R.string.url));
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                int serverResponseCode = uploadFile(SDFile1);
                if (serverResponseCode == 200) {
                    Log.i("Success", " is done! ");
                    flagChatting = false;
                    flagTransfer = true;
                    messageServer = "<img";
                    msg = "Image Transfer";
                    recipientStkidGCM = recipientStkid;
                    new regTask().execute("GCM");
                    new regTask2().execute("Last Message!");
                }
            }
        }).start();
        //performCrop(picturePath);
    } else if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
        convertImageUriToFile(imageUri, this);
        SDFile1 = new File(imagePath);

        String extension = "";
        int index = SDFile1.getName().lastIndexOf(".");
        if (index != -1) {
            extension = SDFile1.getName().substring(index + 1);
        }
        Bitmap bmImg = BitmapFactory.decodeFile(imagePath);
        Bitmap resBm = getResizedBitmap(bmImg, 500);
        adapter.add(new StikyChat("", "<img", false, timeSend, "bitmap" + imagePath, 0, 0, "", "", "", resBm,
                SDFile1.getPath()));
        adapter.notifyDataSetChanged();
        lv.setSelection(adapter.getCount() - 1);
        Log.i("SDFile ", " $$$ " + SDFile1.getAbsolutePath());
        upLoadServerUri = getApplicationContext().getResources().getString(R.string.url)
                + "/androidstikyhive/filetransfer.php?fromStikyBee=" + pref.getString("stkid", "")
                + "&toStikyBee=" + recipientStkid + "&message=photo" + "&extension=" + extension + "&type=image"
                + "&dateTime=" + URLEncoder.encode(timeSendServer) + "&url="
                + URLEncoder.encode(getResources().getString(R.string.url));
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                int serverResponseCode = uploadFile(SDFile1);
                if (serverResponseCode == 200) {
                    Log.i("Success", " is done! ");
                    flagChatting = false;
                    flagTransfer = true;
                    messageServer = "<img";
                    msg = "Image Transfer";
                    recipientStkidGCM = recipientStkid;
                    new regTask().execute("GCM");
                    new regTask2().execute("Last Message!");
                }
            }
        }).start();
    }
}

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

/**
 * Return a scaled bitmap based on the target width and height
 * /*from  w w  w . j  a v a 2 s  .  co m*/
 * @param imagePath
 * @return
 */
private Bitmap getScaledBitmap(String imagePath) {
    // If no new width or height were specified return the original bitmap
    if (this.targetWidth <= 0 && this.targetHeight <= 0) {
        return BitmapFactory.decodeFile(imagePath);
    }

    // figure out the original width and height of the image
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(imagePath, options);

    // determine the correct aspect ratio
    int[] widthHeight = calculateAspectRatio(options.outWidth, options.outHeight);

    // Load in the smallest bitmap possible that is closest to the size we
    // want
    options.inJustDecodeBounds = false;
    options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, this.targetWidth,
            this.targetHeight);
    Bitmap unscaledBitmap = BitmapFactory.decodeFile(imagePath, options);
    if (unscaledBitmap == null) {
        return null;
    }

    return Bitmap.createScaledBitmap(unscaledBitmap, widthHeight[0], widthHeight[1], true);
}