예제 #1
2
  // save image
  public void saveBitmap(Bitmap bm) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HHmm", Locale.UK);
    Date now = new Date();
    String fileName = formatter.format(now) + ".png";
    File f;
    try {
      cameraPath =
          Environment.getExternalStorageDirectory().toString()
              + File.separator
              + "Pictures"
              + File.separator
              + fileName;
      f = new File(cameraPath);
      FileOutputStream out = new FileOutputStream(f);
      bm.compress(Bitmap.CompressFormat.PNG, 90, out);
      out.flush();
      out.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    try {
      uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bm, null, null));
      // MediaStore.Images.Media.insertImage(this.getContentResolver(), cameraPath, fileName, null);
      // CameraActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
      // Uri.fromFile(new File(cameraPath))));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #2
0
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST
        && resultCode == Activity.RESULT_OK
        && data != null
        && data.getData() != null) {
      Uri uri = data.getData();
      try {
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] image = stream.toByteArray();
        ParseFile imageFile = new ParseFile("something.png", image);
        Upload upload = new Upload();
        upload.setMedia(imageFile);
        upload.setUserID(ParseUser.getCurrentUser().getObjectId());
        upload.setComment("");
        thisUploads.add(upload);
        newUploads.add(upload);
        adapter.notifyDataSetChanged();

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;

    try {
      // Load picture from camera and scale/crop it to at most 640x400
      Uri imgFile = Uri.fromFile(new File(getExternalFilesDir(null), "temp.jpg"));
      Bitmap img = MediaStore.Images.Media.getBitmap(getContentResolver(), imgFile);

      int newHeight = (int) ((float) img.getHeight() / (float) img.getWidth() * 640.0f);
      img = Bitmap.createScaledBitmap(img, 640, newHeight, true);

      if (img.getHeight() > 400) {
        img = Bitmap.createBitmap(img, 0, (img.getHeight() - 400) / 2, img.getWidth(), 400);
      }

      System.gc();

      // Store picture with user
      if (mUser != null) {
        try {
          mUser.put("picture_updated", true);
          mUser.put("picture", Util.encodePicture(img));
        } catch (JSONException e) {
          Log.e(TAG, e.toString());
        }
      }

      // Show picture
      mPicture = img;
      onPictureUpdated();
    } catch (IOException e) {
      Log.e(TAG, e.toString());
    }
  }
예제 #4
0
 @Override
 protected String doInBackground(Bitmap... params) {
   String result = "图片保存失败";
   try {
     String sdcard = Environment.getExternalStorageDirectory().toString();
     String fileName = System.currentTimeMillis() + ".png";
     File file = new File(sdcard + "/Download", fileName);
     if (!file.exists()) {
       file.mkdirs();
     }
     File imageFile = new File(file.getAbsolutePath(), new Date().getTime() + ".jpg");
     FileOutputStream fileOutputStream = null;
     fileOutputStream = new FileOutputStream(imageFile);
     Bitmap image = params[0];
     image.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
     fileOutputStream.flush();
     fileOutputStream.close();
     result = String.format("图片保存到%s", file.getAbsolutePath());
     // 其次把文件插入到系统图库
     MediaStore.Images.Media.insertImage(
         mContext.getContentResolver(), file.getAbsolutePath(), fileName, null);
     // 最后通知图库更新
     mContext.sendBroadcast(
         new Intent(
             Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
             Uri.parse("file://" + file.getAbsolutePath())));
   } catch (Exception e) {
     e.printStackTrace();
   }
   return result;
 }
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
      /*
       * Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data");
       * imageToSend = imageBitmap; //mImageView.setImageBitmap(imageBitmap);
       * //SendBitmapTaskFTP sendToFTP = new SendBitmapTaskFTP(); //sendToFTP.execute();
       * SendBitmapTask sendImage = new SendBitmapTask(); sendImage.execute();
       */
      /*
       * if(data == null){ File file = new File(imageUri.getPath()); fileToSend = file;
       * SendBitmapTask sendImage = new SendBitmapTask(); //sendImage.execute();
       * Log.d("CameraDemo", "Pic saved"); }
       */

      Uri fullPhotoUri = data.getData();

      try {
        Bitmap bm = MediaStore.Images.Media.getBitmap(this.getContentResolver(), fullPhotoUri);
        imageToSend = getResizedBitmap(bm, 1000);
        SendBitmapTask sendImage = new SendBitmapTask();
        sendImage.execute();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        // e.printStackTrace();
        Toast.makeText(getApplicationContext(), fullPhotoUri.getPath(), Toast.LENGTH_SHORT).show();
      }

      // Toast.makeText(getApplicationContext(), fullPhotoUri.getPath() ,
      // Toast.LENGTH_SHORT).show();
    }
  }
예제 #6
0
  /**
   * Выбираем изображение из галереи телефона и сохраняем в imageView.
   *
   * @param requestCode
   * @param resultCode
   * @param data
   */
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    Bitmap galleryPic = null;

    switch (requestCode) {
      case GALLERY_EQUIPMENT_REQUEST:
        if (resultCode == getActivity().RESULT_OK) {
          Uri selectedImage = data.getData();
          try {
            galleryPic =
                MediaStore.Images.Media.getBitmap(
                    getActivity().getContentResolver(), selectedImage);
          } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          getImage().setImageBitmap(galleryPic);
        }
    }
  }
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST
        && resultCode == RESULT_OK
        && data != null
        && data.getData() != null) {
      Uri filePath = data.getData();
      try {
        // Getting the Bitmap from Gallery
        bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
        // String image = getStringImage(bitmap);
        Bitmap img_oval = getCroppedBitmap(bitmap);

        /** ******************** Imagen Final ******************* */
        // Setting the Bitmap to ImageView
        imageView.setImageBitmap(img_oval);

      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      Toast.makeText(this, "Tamaño maximo superado", Toast.LENGTH_LONG).show();
    }
  }
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
      case 1001: // 历史地址
        if (data != null) {
          picUrl = data.getStringExtra("persion_imag");
          if (!TextUtils.isEmpty(picUrl)) {
            try {
              Bitmap bitmap =
                  MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(picUrl));
              ByteArrayOutputStream bao = new ByteArrayOutputStream();
              bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
              byte[] ba = bao.toByteArray();
              img64 = Base64.encodeBytes(ba);
            } catch (FileNotFoundException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
        }

        break;
      case 1:
        break;

      default:
        break;
    }
  };
예제 #9
0
 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
   Log.i(TAG, " requestcode: " + requestCode);
   Log.i(TAG, " resultCode: " + resultCode);
   switch (requestCode) {
     case 100:
       if (resultCode == Activity.RESULT_OK) {
         Uri selectedImage = imageUri;
         getActivity().getContentResolver().notifyChange(selectedImage, null);
         ContentResolver cr = getActivity().getContentResolver();
         Bitmap bitmap;
         try {
           bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
           imgFavorite.setImageBitmap(bitmap);
           Log.i(TAG, " butmap " + bitmap.toString());
           Log.i(TAG, " img view " + imgFavorite.toString());
           Log.i(TAG, " img uri " + imageUri.toString());
           imageAdapter.addmThumbIds(imageUri.toString());
         } catch (Exception e) {
           Log.e("Camera", e.toString());
         } finally {
           imageAdapter.notifyDataSetChanged();
         }
       }
   }
 }
예제 #10
0
  private void shareComicImage() {
    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("image/*");
    Bitmap mBitmap = mComicMap.get(sFavoriteIndex).getBitmap();
    try {
      String path =
          MediaStore.Images.Media.insertImage(
              getActivity().getContentResolver(), mBitmap, "Image Description", null);
      share.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
    } catch (Exception e) {
      try {
        File cachePath = new File(getActivity().getCacheDir(), "images");
        cachePath.mkdirs(); // don't forget to make the directory
        FileOutputStream stream = new FileOutputStream(cachePath + "/image.png");
        mBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        stream.close();

        File imagePath = new File(getActivity().getCacheDir(), "images");
        File newFile = new File(imagePath, "image.png");
        Uri contentUri =
            FileProvider.getUriForFile(
                getActivity(), "com.gadgetmonks.carntoonage.fileprovider", newFile);

        share.putExtra(Intent.EXTRA_STREAM, contentUri);
      } catch (IOException e2) {
        e.printStackTrace();
      }
    }
    if (PrefHelper.shareAlt()) {
      share.putExtra(Intent.EXTRA_TEXT, PrefHelper.getAlt(sFavorites[sFavoriteIndex]));
    }
    startActivity(Intent.createChooser(share, this.getResources().getString(R.string.share_image)));
  }
예제 #11
0
  /* (non-Javadoc)
   * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
   */
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case MENU_EVOLUTION:
        this.showDialog(DIALOG_SELECT_TIME_STEP);
        return true;
      case MENU_HOME:
        Intent i = new Intent(this, OmbreActivity.class);
        this.startActivity(i);
        return true;
      case MENU_SAVE:
        Bitmap bitmap = Bitmap.createBitmap(this.controller.getBitmap());
        Canvas canvas = new Canvas(bitmap);

        // Draw the shadows
        new ResultDrawable(this.controller).draw(canvas);

        // Draw the time of the simulation
        Paint paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setTextSize(24);
        canvas.drawText(dateFormat.format(this.controller.getTime().getTime()), 5, 29, paint);

        MediaStore.Images.Media.insertImage(this.getContentResolver(), bitmap, "Result", "Result");
        return true;
    }

    return super.onOptionsItemSelected(item);
  }
 public static Uri getImageUri(Context inContext, Bitmap inImage) {
   ByteArrayOutputStream bytes = new ByteArrayOutputStream();
   inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
   String path =
       MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
   return Uri.parse(path);
 }
예제 #13
0
    @TargetApi(CAMERA_2_API_LIMIT)
    @Override
    public void run() {
      ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
      byte[] bytes = new byte[buffer.remaining()];
      buffer.get(bytes);
      FileOutputStream output = null;
      try {
        output = new FileOutputStream(mFile);
        output.write(bytes);

        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
        final String timestampFilename = dateFormat.format(date);
        // http://stackoverflow.com/a/8722494/4326052
        String imagePath =
            new File(mActivity.getExternalFilesDir(null), timestampFilename + ".jpg")
                .getAbsolutePath();
        MediaStore.Images.Media.insertImage(
            mActivity.getContentResolver(), bitmap, timestampFilename, "Picture taken by shoutake");

      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        mImage.close();
        if (null != output) {
          try {
            output.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    }
예제 #14
0
 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
   // TODO Auto-generated method stub
   if (resultCode == Activity.RESULT_OK) {
     switch (requestCode) {
       case C.ActivityRequest.REQUEST_SELECT_CITY_ACTIVITY:
         String province = data.getStringExtra("provinceText");
         String city = data.getStringExtra("cityText");
         editArea.setText(province + " " + city);
         break;
       case C.ActivityRequest.REQUEST_SELECT_CAMERA_ACTIVITY:
         Uri cropUri = data.getParcelableExtra("cropPicUri");
         imgPath = cropUri.getPath();
         try {
           Bitmap bmp = MediaStore.Images.Media.getBitmap(this.getContentResolver(), cropUri);
           editAvatar.setImageBitmap(bmp);
         } catch (FileNotFoundException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
         } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
         }
         break;
       case C.ActivityRequest.REQUEST_DATE_PICKER_ACTIVITY:
         String birthday = data.getStringExtra("birthday");
         editBirthday.setText(birthday);
         break;
       case C.ActivityRequest.REQUEST_SELECT_GENDER:
         editSex.setText(data.getStringExtra("gender"));
         break;
     }
   }
 }
예제 #15
0
  /**
   * 压缩图片到指定大小以内用于附件上传
   *
   * @param context 上下文
   * @param oriImageUri 原始图片 Uri
   * @param fileSize 最大文件大小
   * @return 新得到的图片的 Uri
   */
  public static Uri compressImage(Context context, Uri oriImageUri, int fileSize) {
    try {
      // 压缩图片到指定大小
      Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), oriImageUri);

      double targetWidth = Math.sqrt(fileSize * 1000);
      if (bitmap.getWidth() > targetWidth || bitmap.getHeight() > targetWidth) {
        // 创建操作图片用的 matrix 对象
        Matrix matrix = new Matrix();

        // 计算宽高缩放率
        double x = Math.min(targetWidth / bitmap.getWidth(), targetWidth / bitmap.getHeight());

        // 缩放图片动作
        matrix.postScale((float) x, (float) x);
        bitmap =
            Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
      }

      return saveImageToTmpPath(context, bitmap);
    } catch (IOException e) {
      String message = "saveImageToTmpPath >> 压缩图片到指定大小以内用于附件上传失败";
      Log.e(TAG, message, e);
      CommonUtils.debugToast(context, message);
      return null;
    }
  }
예제 #16
0
  // 保存并通知系统图库更新
  public void saveImageToGallery(Bitmap bmp, String fileName) {
    // 首先保存图片
    File appDir = new File(ALBUM_PATH);
    if (!appDir.exists()) {
      appDir.mkdir();
    }
    File file = new File(ALBUM_PATH, fileName);
    try {
      FileOutputStream fos = new FileOutputStream(file);
      bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
      fos.flush();
      fos.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    // 其次把文件插入到系统图库
    try {
      MediaStore.Images.Media.insertImage(
          PictureActivity.this.getContentResolver(), file.getAbsolutePath(), fileName, null);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    // 最后通知图库更新
    String path = ALBUM_PATH + fileName;
    System.out.println("path : " + path);
    PictureActivity.this.sendBroadcast(
        new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
  }
예제 #17
0
 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   switch (requestCode) {
     case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
       if (resultCode == Activity.RESULT_OK) {
         Uri selectedImage = imageUri;
         AddFragment.this.getActivity().getContentResolver().notifyChange(selectedImage, null);
         imageView = (ImageView) view.findViewById(R.id.imageView2);
         ContentResolver cr = AddFragment.this.getActivity().getContentResolver();
         try {
           Matrix matrix = new Matrix();
           matrix.postRotate(90);
           bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
           Bitmap rotatedBitmap =
               Bitmap.createBitmap(
                   bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
           imageView.setImageBitmap(rotatedBitmap);
           recupLocation();
         } catch (Exception e) {
           Toast.makeText(AddFragment.this.getActivity(), "Failed to load", Toast.LENGTH_SHORT)
               .show();
           Log.e("Camera", e.toString());
         }
       }
   }
 }
예제 #18
0
  public void ocr_main() {
    Log.v(TAG, "entering tess");

    // Getting uri of image/cropped image
    try {
      myimage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), image_uri);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    // Log.v(TAG, "bitmap " + myimage.getByteCount());
    //        Bitmap argb = myimage;
    //        argb = argb.copy(Bitmap.Config.ARGB_8888, true);
    //        Log.v(TAG, "bitmap after argb:" + argb.getByteCount());
    //
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inSampleSize = 2;
    myimage = BitmapFactory.decodeFile(filepath, opt);
    // Log.v(TAG, "bitmap after comp:" + myimage.getByteCount());

    // TessBase starts
    TessBaseAPI baseApi = new TessBaseAPI();

    baseApi.setDebug(true);
    baseApi.init(DATA_PATH, lang);
    Log.v(TAG, "Before baseApi");
    baseApi.setImage(myimage);
    Log.v(TAG, "Before baseApi2");
    String recognizedText = baseApi.getUTF8Text();
    Log.v(TAG, "Before baseApi3");
    baseApi.end();

    Log.v(TAG, "OCRED TEXT: " + recognizedText);

    if (lang.equalsIgnoreCase("eng")) {
      recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+", " ");
    }

    // recognizedText is the final OCRed text
    recognizedText = recognizedText.trim();

    //		String ocrtext = "And...BAM! OCRed: " + recognizedText;
    //		Toast toast = Toast.makeText(this.getApplicationContext(), ocrtext,
    //				Toast.LENGTH_LONG);
    //		toast.show();

    // deleting temporary crop file created
    File file =
        new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "temp.bmp");
    boolean deleted = file.delete();
    Log.i(TAG, "File deleted: " + deleted);

    Intent intent = new Intent(this, ResultActivity.class);
    intent.putExtra("ocrText", recognizedText);
    startActivity(intent);
  }
예제 #19
0
  private void loadTask() {
    String dataString = "";
    if (task.repetition != null) dataString += "Repetitions: " + task.repetition + '\n';
    if (task.holdTime != null) dataString += "Hold Time: " + task.holdTime + '\n';

    data.setText(dataString);

    txt.setText(task.longName);
    des.setText(task.text);

    anima = new AnimationDrawable();
    Log.e("tag", "IdddddO Exception");
    try {
      Log.e("tag", "" + task.getFrames().get(0));
      still =
          new BitmapDrawable(
              MediaStore.Images.Media.getBitmap(getContentResolver(), task.getFrames().get(0)));
    } catch (FileNotFoundException e1) {
      Log.e("tag", "File Not Found");
    } catch (IOException e1) {
      Log.e("tag", "IO Exception");
    }
    Log.e("tag", "IdddddO Exception");
    int w = still.getIntrinsicWidth();
    int h = still.getIntrinsicHeight();
    img.setMinimumWidth(w * 2);
    img.setMinimumHeight(h * 2);
    Log.e("tag", "Safe ");
    for (int i = 0; i < task.getFrames().size(); i++) {
      Bitmap temp1;
      try {
        temp1 = MediaStore.Images.Media.getBitmap(getContentResolver(), task.getFrames().get(i));
        Log.i("tag", "hello1");
        BitmapDrawable drw = new BitmapDrawable(temp1);
        img.setBackgroundDrawable(drw);
        anima.addFrame(drw, task.frameTimes.get(i) * 1000);
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {

        e.printStackTrace();
      }
    }
    Log.i("tag", "hello");
    img.setBackgroundDrawable(still);
  }
예제 #20
0
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != RESULT_OK) {
      return;
    }
    Bitmap bm = null;
    ContentResolver resolver = getContentResolver();
    if (requestCode == REQUEST_CODE_PICK_IMAGE) {
      try {
        bm = null;
        Uri originalUri = data.getData();
        bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(originalUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index);
        Toast.makeText(getBaseContext(), "pick:" + path, Toast.LENGTH_SHORT).show();
        Bitmap bt = convertToBitmap(path, 100, 120);

        profile_circleimageview.setImageDrawable(new BitmapDrawable(bt));
        saveBitmap(bt);

      } catch (IOException e) {
      }
    } else if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
      //  Bitmap bt=convertToBitmap(path,100,120);
      bm = null;
      try {
        Uri originalUri = data.getData();
        bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(originalUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index);
        Bitmap bt = convertToBitmap(path, 100, 120);
        // Toast.makeText(getBaseContext(),"take:"+path,Toast.LENGTH_SHORT).show();
        profile_circleimageview.setImageDrawable(new BitmapDrawable(bt));
        saveBitmap(bt);

      } catch (IOException e) {
        Toast.makeText(getBaseContext(), "Exception", Toast.LENGTH_SHORT).show();
      }
    }
  }
 /**
  * 获得照片的绝对路径
  *
  * @param uri 拍照或者选取照片返回的数据
  * @return 返回字符串
  */
 private String getImagePath(final Uri uri) {
   String[] projection = {MediaStore.Images.Media.DATA};
   Cursor cursor = MediaStore.Images.Media.query(getContentResolver(), uri, projection);
   cursor.moveToFirst();
   String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
   cursor.close();
   return path;
 }
예제 #22
0
 /**
  * @param context
  * @param bitmap
  * @return
  * @brief methods for getting file uri from bitmap
  */
 public static Uri getUriFromBitmap(Context context, Bitmap bitmap) {
   ByteArrayOutputStream bytes = new ByteArrayOutputStream();
   bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
   String path =
       MediaStore.Images.Media.insertImage(
           context.getContentResolver(), bitmap, "image_share", null);
   return Uri.parse(path);
 }
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    switch (requestCode) {
      case CATEGORY_REQUEST:
        if (resultCode == RESULT_OK) {
          loggedUser.setMajorJobCategory(intent.getStringExtra("major"));
          loggedUser.setMinorJobCategory(intent.getStringExtra("minor"));
          displayCategory();
        }
        break;
      case SKILL_REQUEST:
        if (resultCode == RESULT_OK) {
          loggedUser.setSkills(intent.getStringExtra("strongestSkillsList"));
          displaySkill();
        }
        break;
      case PROFILE_PIC_REQUEST:
        if (resultCode == RESULT_OK) {
          Uri selectedImage = imageUri;

          if (selectedImage != null) {
            getContentResolver().notifyChange(selectedImage, null);

            try {
              OutputStream fOut = null;

              Bitmap bitmap =
                  MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
              Bitmap resizedImage = GraphicUtils.resizeProfileImage(bitmap);

              File file = new File(new URI(selectedImage.toString()));
              fOut = new FileOutputStream(file);

              // Set picture compression
              resizedImage.compress(CompressFormat.JPEG, 70, fOut);
              fOut.flush();
              fOut.close();

            } catch (IOException e) {
            } catch (URISyntaxException e) {
            }

            // Upload user Photo
            exe.uploadUserProfilePhoto();

          } else {
            new CustomDialog(
                    ActivitySettings.this,
                    "Info",
                    "Unable to save picture! We are working on that...")
                .show();
          }
        }

        break;
    }
  }
예제 #24
0
 private Bitmap prepareImage(String uri) throws IOException {
   Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(uri));
   ;
   // rotate bitmap
   Matrix matrix = new Matrix();
   matrix.postRotate(getExifOrientation(uri));
   // create new rotated bitmap
   return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
 }
예제 #25
0
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // The preferences returned if the request code is what we had given
    // earlier in startSubActivity
    switch (requestCode) {
      case REQUEST_CODE_CAMERA:
        setRequestedOrientation(
            ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); // pull it out of landscape mode
        break;

      case REQUEST_CODE_IMAGE:
        if (resultCode != RESULT_OK) {
          return;
        }
        Uri uri = data.getData();
        Bitmap b = null;
        try {
          b = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
        } catch (FileNotFoundException e) {
          break;
        } catch (IOException e) {
          break;
        }
        ByteArrayOutputStream byteArrayos = new ByteArrayOutputStream();
        try {
          b.compress(CompressFormat.JPEG, 75, byteArrayos);
          byteArrayos.flush();
        } catch (OutOfMemoryError e) {
          break;
        } catch (IOException e) {
          break;
        }
        filename = "android_pic_upload" + randomString() + ".jpg";
        ImageManager.writeImage(byteArrayos.toByteArray(), filename);
        UshahidiService.fileName = filename;
        selectedPhoto.setText(UshahidiService.fileName);
        break;

      case VIEW_MAP:
        if (resultCode != RESULT_OK) {
          return;
        }

        bundle = null;
        extras = data.getExtras();
        if (extras != null) bundle = extras.getBundle("locations");

        if (bundle != null && !bundle.isEmpty()) {
          incidentLocation.setText(bundle.getString("location"));

          AddIncident.latitude = bundle.getDouble("latitude");
          AddIncident.longitude = bundle.getDouble("longitude");
        }
        break;
    }
  }
예제 #26
0
      @Override
      public void onClick(View v) {
        // TODO: Check flag
        final Album album = mAlbums.get(getAdapterPosition());
        mCountPhotos = mImageUris.size();
        if (mSendPhoto) {
          mProgressDialog.show();
          for (Uri imageUri : mImageUris) {
            try {
              final Bitmap bitmap =
                  MediaStore.Images.Media.getBitmap(
                      SearchableActivity.this.getContentResolver(), imageUri);

              ByteArrayOutputStream stream = new ByteArrayOutputStream();
              bitmap.compress(Bitmap.CompressFormat.JPEG, 20, stream);
              final byte[] data = stream.toByteArray();

              ParseFile file = new ParseFile("teste.jpg", data);

              file.saveInBackground(
                  new SaveCallback() {
                    public void done(ParseException e) {
                      // Handle success or failure here ...
                      mCountPhotos--;
                      if (mCountPhotos == 0) {
                        mProgressDialog.dismiss();
                      }
                    }
                  },
                  new ProgressCallback() {
                    public void done(Integer percentDone) {
                      // Update your progress spinner here. percentDone will be between 0 and 100.
                    }
                  });

              Photo photo = new Photo();
              photo.setImage(file);
              photo.setAlbum(album);
              photo.setAuthor(ParseUser.getCurrentUser());
              photo.saveInBackground();

            } catch (IOException e) {
              e.printStackTrace();
            }
            mSendPhoto = false;
          }

        } else {
          Intent intent = new Intent(SearchableActivity.this, AlbumDetailActivity.class);
          intent.putExtra(AlbumDetailActivity.ALBUM_ID_EXTRA, album.getObjectId());
          intent.putExtra(AlbumDetailActivity.ALBUM_NAME_EXTRA, album.getName());
          startActivity(intent);
        }
      }
예제 #27
0
  @Test
  public void decodeUri_shouldGetWidthAndHeightFromHints() throws Exception {
    ShadowBitmapFactory.provideWidthAndHeightHints(Uri.parse("content:/path"), 123, 456);

    Bitmap bitmap =
        MediaStore.Images.Media.getBitmap(
            Robolectric.application.getContentResolver(), Uri.parse("content:/path"));
    assertEquals("Bitmap for content:/path", shadowOf(bitmap).getDescription());
    assertEquals(123, bitmap.getWidth());
    assertEquals(456, bitmap.getHeight());
  }
  public static Uri getImage(ImageView image, ContentResolver contentResolver) {
    MediaStoreHelper.initMediaDir();

    Drawable mDrawable = image.getDrawable();
    Bitmap mBitmap = ((BitmapDrawable) mDrawable).getBitmap();

    String path =
        MediaStore.Images.Media.insertImage(contentResolver, mBitmap, "Image Description", null);

    Uri uri = Uri.parse(path);
    return uri;
  }
예제 #29
0
  public static String getPathOfPhotoByUri(Context context, Uri uri) {
    String[] filePathColumn = {MediaStore.Images.Media.DATA};

    Cursor cursor =
        MediaStore.Images.Media.query(context.getContentResolver(), uri, filePathColumn);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String picturePath = cursor.getString(columnIndex);
    cursor.close();
    return picturePath;
  }
예제 #30
-1
  /**
   * 获得选中相册的图片
   *
   * @param mContext 上下文
   * @param data onActivityResult返回的Intent
   * @return
   */
  public static Bitmap getChoosedImage(Activity mContext, Intent data) {
    if (data == null) {
      return null;
    }

    Bitmap bm = null;

    // 外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
    ContentResolver resolver = mContext.getContentResolver();

    // 此处的用于判断接收的Activity是不是你想要的那个
    try {
      Uri originalUri = data.getData(); // 获得图片的uri
      bm = MediaStore.Images.Media.getBitmap(resolver, originalUri); // 显得到bitmap图片
      // 这里开始的第二部分,获取图片的路径:
      String[] proj = {MediaStore.Images.Media.DATA};
      // 好像是android多媒体数据库的封装接口,具体的看Android文档
      Cursor cursor = mContext.managedQuery(originalUri, proj, null, null, null);
      // 按我个人理解 这个是获得用户选择的图片的索引值
      int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
      // 将光标移至开头 ,这个很重要,不小心很容易引起越界
      cursor.moveToFirst();
      // 最后根据索引值获取图片路径
      String path = cursor.getString(column_index);
      // 不用了关闭游标
      cursor.close();
    } catch (Exception e) {
      Log.e("ToolPhone", e.getMessage());
    }

    return bm;
  }