Пример #1
0
  private void savePhotos() {
    try {
      saveMemo(1);

      realm.beginTransaction();
      Photo photo = new Photo();
      photo.setId(getPhotoId());
      photo.setSource("memo");
      photo.setCreateTime(new Date());
      photo.setCreateUser(ConstUtils.USER_NAME);
      photo.setMyPosition(ConstUtils.MY_POSITION);
      photo.setRelationId(addMemo.getId());
      Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
      Log.d("AddMemoActivity", "width: " + bitmap.getWidth());
      Log.d("AddMemoActivity", "height: " + bitmap.getHeight());
      if (bitmap.getWidth() < bitmap.getHeight()) {
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, 660, 1173);
      } else {
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, 1173, 660);
      }

      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      bitmap.compress(Bitmap.CompressFormat.JPEG, 95, bos); // 参数100表示不压缩
      byte[] photoBytes = bos.toByteArray();
      photo.setPhoto(photoBytes);
      realm.copyToRealm(photo);
      realm.commitTransaction();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
Пример #2
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_developer);

    toolbar = (Toolbar) findViewById(R.id.tool_bar);
    setSupportActionBar(toolbar);

    assert getSupportActionBar() != null;
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    img1 = (ImageView) findViewById(R.id.view);
    img2 = (ImageView) findViewById(R.id.view2);
    img3 = (ImageView) findViewById(R.id.view3);
    img4 = (ImageView) findViewById(R.id.view4);
    img5 = (ImageView) findViewById(R.id.view5);

    Bitmap bit = BitmapFactory.decodeResource(getResources(), R.drawable.bb);
    Bitmap ThumbImage = ThumbnailUtils.extractThumbnail(bit, thumbsize, thumbsize);
    img1.setImageBitmap(ThumbImage);
    Bitmap bit2 = BitmapFactory.decodeResource(getResources(), R.drawable.aa);
    Bitmap ThumbImage2 = ThumbnailUtils.extractThumbnail(bit2, thumbsize, thumbsize);
    img2.setImageBitmap(ThumbImage2);
    Bitmap bit3 = BitmapFactory.decodeResource(getResources(), R.drawable.aa);
    Bitmap ThumbImage3 = ThumbnailUtils.extractThumbnail(bit3, thumbsize, thumbsize);
    img3.setImageBitmap(ThumbImage3);
    Bitmap bit4 = BitmapFactory.decodeResource(getResources(), R.drawable.cc);
    Bitmap ThumbImage4 = ThumbnailUtils.extractThumbnail(bit4, thumbsize, thumbsize);
    img4.setImageBitmap(ThumbImage4);
    Bitmap bit5 = BitmapFactory.decodeResource(getResources(), R.drawable.hh);
    Bitmap ThumbImage5 = ThumbnailUtils.extractThumbnail(bit5, thumbsize, thumbsize);
    img5.setImageBitmap(ThumbImage5);
  }
Пример #3
0
 public UFile(String path) {
   try {
     file = new File(path);
     this.path = file.getPath();
     this.name = file.getName();
     size = file.length();
     thumbNail = null;
     if (isMovie()) {
       MediaMetadataRetriever retriever = new MediaMetadataRetriever();
       retriever.setDataSource(path);
       String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
       movieLength = Long.parseLong(time);
       thumbNail =
           ThumbnailUtils.createVideoThumbnail(
               path, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);
     } else if (isImage()) {
       Bitmap temp = BitmapFactory.decodeFile(file.getPath());
       float scale = context.getResources().getDisplayMetrics().densityDpi / 160f;
       thumbNail =
           ThumbnailUtils.extractThumbnail(temp, (int) (50f * scale), (int) (50f * scale));
     } else if (file.isDirectory()) {
       thumbNail = BitmapFactory.decodeResource(null, R.mipmap.docu);
     }
   } catch (Exception e) {
     file = null;
   }
 }
Пример #4
0
 private Bitmap getVideoBitmap(String path) {
   Bitmap bitmap;
   bitmap = ThumbnailUtils.createVideoThumbnail(path, MediaStore.Images.Thumbnails.MICRO_KIND);
   bitmap =
       ThumbnailUtils.extractThumbnail(bitmap, 200, 200, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
   return bitmap;
 }
  protected void onCreateIcons() {
    ImageView icon_small = (ImageView) getOptionView().findViewById(R.id.icon_small);
    ImageView icon_big = (ImageView) getOptionView().findViewById(R.id.icon_big);
    Resources res = getContext().getBaseContext().getResources();

    if (null != res) {
      int id =
          res.getIdentifier(
              "feather_tool_icon_" + mResourceName,
              "drawable",
              getContext().getBaseContext().getPackageName());
      if (id > 0) {

        Bitmap big, small;

        try {
          Bitmap bmp = BitmapFactory.decodeResource(res, id);
          big =
              ThumbnailUtils.extractThumbnail(
                  bmp, (int) (bmp.getWidth() / 1.5), (int) (bmp.getHeight() / 1.5));
          bmp.recycle();
          small =
              ThumbnailUtils.extractThumbnail(
                  big, (int) (big.getWidth() / 1.5), (int) (big.getHeight() / 1.5));
        } catch (OutOfMemoryError e) {
          e.printStackTrace();
          return;
        }
        icon_big.setImageBitmap(big);
        icon_small.setImageBitmap(small);
      }
    }
  }
 /**
  * 获取视频缩略图
  *
  * @param videoPath
  * @param width
  * @param height
  * @param kind
  * @return
  */
 private Bitmap getVideoThumbnail(String videoPath, int width, int height, int kind) {
   Bitmap bitmap = null;
   bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
   bitmap =
       ThumbnailUtils.extractThumbnail(
           bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
   return bitmap;
 }
Пример #7
0
 /**
  * 获取缩略图
  *
  * @param url
  * @param width
  * @param height
  * @return
  */
 private Bitmap getVideoThumbnail(String videoPath, int width, int height) {
   Bitmap bitmap = null;
   // 获取视频的缩略图
   bitmap =
       ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Images.Thumbnails.MICRO_KIND);
   bitmap =
       ThumbnailUtils.extractThumbnail(
           bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
   return bitmap;
 }
  /**
   * Executes the request and returns PluginResult.
   *
   * @param action The action to execute.
   * @param args JSONArry of arguments for the plugin.
   * @param callbackId The callback id used when calling back into JavaScript.
   * @return A PluginResult object with a status and message.
   */
  @Override
  public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    try {
      if (action.equals("createVideoThumbnail")) {
        String pvUrl = args.getString(0);
        if (pvUrl != null && pvUrl.length() > 0) {
          // do smth with pvUrl

          // MINI_KIND: 512 x 384 thumbnail
          Bitmap bmThumbnail = ThumbnailUtils.createVideoThumbnail(pvUrl, Thumbnails.MINI_KIND);

          try {
            FileOutputStream out = new FileOutputStream(pvUrl + ".jpg");
            bmThumbnail.compress(Bitmap.CompressFormat.JPEG, 55, out);
            //	                	       File file = new File(pvUrl + ".jpg");
            //	                	       boolean val = file.exists();

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

          callbackContext.success(pvUrl + ".jpg");
          return true;
        }
      } else {
        if (action.equals("createImageThumbnail")) {
          String pvUrl = args.getString(0);
          if (pvUrl != null && pvUrl.length() > 0) {
            // do smth with pvUrl

            Bitmap bitmap = BitmapFactory.decodeFile(pvUrl);

            Bitmap bmThumbnail = ThumbnailUtils.extractThumbnail(bitmap, 512, 384);

            try {
              FileOutputStream out = new FileOutputStream(pvUrl + ".jpg");
              bmThumbnail.compress(Bitmap.CompressFormat.JPEG, 55, out);
            } catch (Exception e) {
              e.printStackTrace();
            }

            callbackContext.success(pvUrl + ".jpg");
            return true;
          }
        }
      }

    } catch (JSONException e) {

    }
    return false;
  }
  /*
   * Method called after returning from Gallery or Camera
   */
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {

      if (requestCode == STATUS_GALLERY && resultCode == RESULT_OK && null != data) {

        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String imgDecodableString = cursor.getString(columnIndex);
        cursor.close();
        picturePath = imgDecodableString;
      }
    } catch (Exception e) {
      Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
    }

    Bitmap bitmap =
        ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(picturePath), 200, 200);
    vPicture.setImageBitmap(bitmap);
  }
Пример #10
0
  /** Helper function to get the thumbnail */
  public static final Bitmap getImageThumbnail(File file) {

    /** Set bitmap size. */
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 4;

    File thumbfile =
        new File(
            file.getParentFile().getAbsolutePath()
                + SyncGalleryConstants.Gallery_THUMBNAILS
                + file.getName());
    if (thumbfile.exists()) {
      /** Retrieve from the thumbnail folder */
      return BitmapFactory.decodeFile(thumbfile.getAbsolutePath());
    } else {
      /** Create the thumbnail based on orignal image */
      Bitmap image = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
      Bitmap thumbnail = ThumbnailUtils.extractThumbnail(image, 100, 100);
      if (thumbnail != null) {
        /** Save it to thumbnail folder for future use */
        saveBitMap(thumbnail, file);
      }
      return thumbnail;
    }
  }
Пример #11
0
 private Bitmap createVideoThumbnail(String url) {
   Bitmap bitmap = null;
   MediaMetadataRetriever retriever = new MediaMetadataRetriever();
   int kind = MediaStore.Video.Thumbnails.MINI_KIND;
   try {
     if (Build.VERSION.SDK_INT >= 14) {
       retriever.setDataSource(url, new HashMap<String, String>());
     } else {
       retriever.setDataSource(url);
     }
     bitmap = retriever.getFrameAtTime();
   } catch (IllegalArgumentException ex) {
     // Assume this is a corrupt video file
   } catch (RuntimeException ex) {
     // Assume this is a corrupt video file.
   } finally {
     try {
       retriever.release();
     } catch (RuntimeException ex) {
       // Ignore failures while cleaning up.
     }
   }
   if (kind == MediaStore.Images.Thumbnails.MICRO_KIND && bitmap != null) {
     bitmap =
         ThumbnailUtils.extractThumbnail(bitmap, 10, 10, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
   }
   return bitmap;
 }
Пример #12
0
  private void createThumbnail(ContentValues map) throws IOException {
    File videoFile = fileFromResourceMap(map);

    Log.d("Creating thumbnail from video file " + videoFile.toString());

    Bitmap bitmap =
        ThumbnailUtils.createVideoThumbnail(
            videoFile.toString(), MediaStore.Video.Thumbnails.MINI_KIND);
    if (bitmap == null) {
      Log.w("Error creating thumbnail");
      return;
    }

    String filename = (String) map.get(Resources.FILENAME);
    if (TextUtils.isEmpty(filename)) {
      throw new IOException("Must specify FILENAME when inserting Resource");
    }
    Uri thumbnailUri = Resources.buildThumbnailUri(filename + THUMBNAIL_EXT);
    OutputStream ostream;
    try {
      ostream = getContext().getContentResolver().openOutputStream(thumbnailUri);
    } catch (FileNotFoundException e) {
      Log.d("Could not open output stream for thumbnail storage: " + e.getLocalizedMessage());
      return;
    }

    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
    ostream.flush();
    IOUtilities.closeStream(ostream);

    map.put(Resources.THUMBNAIL, thumbnailUri.toString());
  }
 @Test
 public void testLocalVideoMiniThumbnailSuccess() throws Exception {
   when(mImageRequest.getPreferredWidth()).thenReturn(100);
   when(mImageRequest.getPreferredHeight()).thenReturn(100);
   when(android.media.ThumbnailUtils.createVideoThumbnail(
           mFile.getPath(), MediaStore.Images.Thumbnails.MINI_KIND))
       .thenReturn(mBitmap);
   doAnswer(
           new Answer() {
             @Override
             public Object answer(InvocationOnMock invocation) throws Throwable {
               mCloseableReference = ((CloseableReference) invocation.getArguments()[0]).clone();
               return null;
             }
           })
       .when(mConsumer)
       .onNewResult(any(CloseableReference.class), eq(true));
   mLocalVideoThumbnailProducer.produceResults(mConsumer, mProducerContext);
   mExecutor.runUntilIdle();
   assertEquals(1, mCloseableReference.getUnderlyingReferenceTestOnly().getRefCountTestOnly());
   assertEquals(
       mBitmap, mCloseableReference.getUnderlyingReferenceTestOnly().get().getUnderlyingBitmap());
   verify(mProducerListener).onProducerStart(mRequestId, PRODUCER_NAME);
   verify(mProducerListener).onProducerFinishWithSuccess(mRequestId, PRODUCER_NAME, null);
 }
Пример #14
0
        public void onPictureTaken(byte[] data, Camera arg1) {

          if (data != null) {
            PictureTaken = true;

            // Extract the bitmap from data
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

            // Only select the region we want
            bitmap =
                ThumbnailUtils.extractThumbnail(
                    bitmap, bitmap.getWidth() / 9, bitmap.getHeight() / 3);

            // Rotate the bitmap
            Matrix matrix = new Matrix();
            matrix.postRotate(90);
            bitmap =
                Bitmap.createBitmap(
                    bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

            // Convert it back to byte array data
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] bmArray = stream.toByteArray(); // Get the underlying pixel bytes array
            image = bmArray;
            if (image != null) {
              Toast.makeText(getActivity(), "Photo Taken", Toast.LENGTH_SHORT).show();
            }
          }
          cameraObject.startPreview();
        }
  private void setVideo() {
    Bitmap image = ThumbnailUtils.createVideoThumbnail(mData.filePath, Video.Thumbnails.MINI_KIND);

    if (image == null) {
      image = BitmapFactory.decodeResource(getResources(), R.drawable.ic_missing_thumbnail_video);
    }

    mContactImage.setImageBitmap(image);
    mContactImage.setVisibility(View.VISIBLE);

    mContactImageLayout.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            Intent mediaIntent = new Intent(Intent.ACTION_VIEW);
            Uri uri = Uri.parse(mData.filePath);
            String type = "video/*";
            mediaIntent.setDataAndType(uri, type);
            mContext.startActivity(mediaIntent);
          }
        });

    mContactImageParent.setOnCreateContextMenuListener(mRecipientsMenuCreateListener);
  }
Пример #16
0
  public void setBitmap(Bitmap bitmap) {
    // Make sure uri and original are consistently both null or both
    // non-null.
    if (bitmap == null) {
      mThumb = null;
      mThumbs = null;
      setImageDrawable(null);
      setVisibility(GONE);
      return;
    }

    LayoutParams param = getLayoutParams();
    final int miniThumbWidth = param.width - getPaddingLeft() - getPaddingRight();
    final int miniThumbHeight = param.height - getPaddingTop() - getPaddingBottom();
    mThumb = ThumbnailUtils.extractThumbnail(bitmap, miniThumbWidth, miniThumbHeight);
    if (mThumbs == null || !mEnableAnimation) {
      mThumbs = new Drawable[2];
      mThumbs[1] = new BitmapDrawable(getContext().getResources(), mThumb);
      setImageDrawable(mThumbs[1]);
    } else {
      mThumbs[0] = mThumbs[1];
      mThumbs[1] = new BitmapDrawable(getContext().getResources(), mThumb);
      mThumbTransition = new TransitionDrawable(mThumbs);
      setImageDrawable(mThumbTransition);
      mThumbTransition.startTransition(500);
    }
    setVisibility(VISIBLE);
  }
Пример #17
0
 /**
  * 获取指定路径下的图片的指定大小的缩略图 getImageThumbnail
  *
  * @return Bitmap
  * @throws
  */
 public static Bitmap getImageThumbnail(String imagePath, int width, int height) {
   Bitmap bitmap = null;
   BitmapFactory.Options options = new BitmapFactory.Options();
   options.inJustDecodeBounds = true;
   // 获取这个图片的宽和高,注意此处的bitmap为null
   bitmap = BitmapFactory.decodeFile(imagePath, options);
   options.inJustDecodeBounds = false; // 设为 false
   // 计算缩放比
   int h = options.outHeight;
   int w = options.outWidth;
   int beWidth = w / width;
   int beHeight = h / height;
   int be = 1;
   if (beWidth < beHeight) {
     be = beWidth;
   } else {
     be = beHeight;
   }
   if (be <= 0) {
     be = 1;
   }
   options.inSampleSize = be;
   // 重新读入图片,读取缩放后的bitmap,注意这次要把options.inJustDecodeBounds 设为 false
   bitmap = BitmapFactory.decodeFile(imagePath, options);
   // 利用ThumbnailUtils来创建缩略图,这里要指定要缩放哪个Bitmap对象
   bitmap =
       ThumbnailUtils.extractThumbnail(
           bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
   return bitmap;
 }
 @Test
 public void testLocalVideoMicroThumbnailSuccess() throws Exception {
   when(mProducerListener.requiresExtraMap(mRequestId)).thenReturn(true);
   when(android.media.ThumbnailUtils.createVideoThumbnail(
           mFile.getPath(), MediaStore.Images.Thumbnails.MICRO_KIND))
       .thenReturn(mBitmap);
   doAnswer(
           new Answer() {
             @Override
             public Object answer(InvocationOnMock invocation) throws Throwable {
               mCloseableReference = ((CloseableReference) invocation.getArguments()[0]).clone();
               return null;
             }
           })
       .when(mConsumer)
       .onNewResult(any(CloseableReference.class), eq(true));
   mLocalVideoThumbnailProducer.produceResults(mConsumer, mProducerContext);
   mExecutor.runUntilIdle();
   assertEquals(1, mCloseableReference.getUnderlyingReferenceTestOnly().getRefCountTestOnly());
   assertEquals(
       mBitmap, mCloseableReference.getUnderlyingReferenceTestOnly().get().getUnderlyingBitmap());
   verify(mProducerListener).onProducerStart(mRequestId, PRODUCER_NAME);
   Map<String, String> thumbnailFoundMap =
       ImmutableMap.of(LocalVideoThumbnailProducer.CREATED_THUMBNAIL, "true");
   verify(mProducerListener)
       .onProducerFinishWithSuccess(mRequestId, PRODUCER_NAME, thumbnailFoundMap);
 }
Пример #19
0
    @Override
    public Bitmap onAfterBitmapDownload(Bitmap downloadBt) {
      if (downloadBt != null && !downloadBt.isRecycled()) {
        return ThumbnailUtils.extractThumbnail(downloadBt, 200, 200);
      }

      return null;
    }
Пример #20
0
 /**
  * 有两种办法将照片加载到bitmap中:2.用照片的真实路径加载
  *
  * @param path 被加载的图像的路径
  * @param width 加载后缩放到的目标宽度
  * @param height 加载后缩放到的目标高度
  * @return 加载并缩放后的位图
  */
 public static Bitmap loadBitmap(String path, int width, int height) {
   Bitmap mBitmap = null;
   BitmapFactory.Options options = new BitmapFactory.Options();
   options.inPreferredConfig = Bitmap.Config.ARGB_8888; // FaceDetecor只能读取RGB 565格式的Bitmap
   Bitmap bitmap = BitmapFactory.decodeFile(path, options);
   mBitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height); // 缩放位图
   return mBitmap;
 }
Пример #21
0
 @Override
 public void onBitmapDownloaded(ImageView holder, Bitmap image) {
   int width = holder.getWidth();
   int height = holder.getHeight();
   Bitmap thumbail =
       ThumbnailUtils.extractThumbnail(
           image, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
   holder.setImageBitmap(thumbail);
 }
 @Test(expected = RuntimeException.class)
 public void testFetchLocalFileFailsByThrowing() throws Exception {
   when(android.media.ThumbnailUtils.createVideoThumbnail(
           mFile.getPath(), MediaStore.Images.Thumbnails.MICRO_KIND))
       .thenThrow(mException);
   verify(mConsumer).onFailure(mException);
   verify(mProducerListener).onProducerStart(mRequestId, PRODUCER_NAME);
   verify(mProducerListener)
       .onProducerFinishWithFailure(mRequestId, PRODUCER_NAME, mException, null);
 }
  private String captureImage() {
    OutputStream output;

    Calendar cal = Calendar.getInstance();

    Bitmap bitmap =
        Bitmap.createBitmap(
            collageEditorRelativeLayout.getWidth(),
            collageEditorRelativeLayout.getHeight(),
            Config.ARGB_8888);

    bitmap =
        ThumbnailUtils.extractThumbnail(
            bitmap,
            collageEditorRelativeLayout.getWidth(),
            collageEditorRelativeLayout.getHeight());

    Canvas b = new Canvas(bitmap);
    collageEditorRelativeLayout.draw(b);

    File baseDir;

    if (android.os.Build.VERSION.SDK_INT < 8) {
      baseDir = Environment.getExternalStorageDirectory();
    } else {
      baseDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    }

    File dir = new File(baseDir, Common.FOLDER_NAME);

    boolean success = true;
    if (!dir.exists()) success = dir.mkdir();

    String tempImageName = cal.getTimeInMillis() + ".jpg";

    // Create a name for the saved image
    file = new File(dir, tempImageName);

    fullScreenImageURL = Uri.fromFile(file).toString();

    try {
      output = new FileOutputStream(file);
      bitmap.compress(Bitmap.CompressFormat.JPEG, 85, output);
      output.flush();
      output.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

    showSuccessDialog(getString(R.string.success), getString(R.string.successMsg));

    displayInterstitial();

    return tempImageName;
  }
Пример #24
0
  private Bitmap getVideoDrawable(String path) throws OutOfMemoryError {

    try {
      Bitmap thumb =
          ThumbnailUtils.createVideoThumbnail(path, MediaStore.Images.Thumbnails.MINI_KIND);
      return thumb;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
Пример #25
0
  public static Bitmap compressImage(Bitmap sourceBitmap, int maxKBSize, int base) {

    Bitmap targetBitmap =
        ThumbnailUtils.extractThumbnail(
            sourceBitmap, sourceBitmap.getWidth() / base, sourceBitmap.getHeight() / base);
    if (KBSizeOf(targetBitmap) <= maxKBSize) {
      return targetBitmap;
    } else {
      return compressImage(sourceBitmap, maxKBSize, base + 1);
    }
  }
Пример #26
0
  private void showUploadSuccessDialog() {
    // set up dialogVideoInfo
    dialogUploadSuccess.setCancelable(true);
    state = 0;
    ImageView iv_thumb = (ImageView) dialogUploadSuccess.findViewById(R.id.iv_thumb);

    LinearLayout ll_video_info =
        (LinearLayout) dialogUploadSuccess.findViewById(R.id.ll_upload_success);
    if (display.getWidth() > display.getHeight()) {
      ll_video_info.getLayoutParams().width = display.getHeight();
      ll_video_info.getLayoutParams().height = (int) Math.round((float) display.getHeight() * 0.7);
    } else {
      ll_video_info.getLayoutParams().width = (int) Math.round((float) display.getWidth() * 0.7);
      ll_video_info.getLayoutParams().height = (int) Math.round((float) display.getHeight() * 0.6);
      iv_thumb.getLayoutParams().height = (int) Math.round((float) display.getHeight() * 0.6) / 2;
    }

    Bitmap bMap =
        ThumbnailUtils.createVideoThumbnail(
            Main.this.pathfromURI, MediaStore.Video.Thumbnails.MICRO_KIND);
    iv_thumb.setScaleType(ImageView.ScaleType.CENTER_CROP);
    iv_thumb.setImageBitmap(bMap);

    // set up button
    ImageView iv_close = (ImageView) dialogUploadSuccess.findViewById(R.id.iv_close);
    iv_close.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
            finish();
            getActivityMediator().showMain();
          }
        });

    Button btn_upload_successfully =
        (Button) dialogUploadSuccess.findViewById(R.id.btn_upload_successfully);
    btn_upload_successfully.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
            finish();
            getActivityMediator().showMain();
          }
        });

    // now that the dialogVideoInfo is set up, it's time to show it
    dialogUploadSuccess.show();
  }
Пример #27
0
 /**
  * 有两种办法将照片加载到bitmap中:1.通过uri用stream的方式
  *
  * @param mContext Context
  * @param uri 资源uri
  * @param width 加载后缩放到的目标宽度
  * @param height 加载后缩放到的目标高度
  * @return 加载并缩放后的位图
  */
 public static Bitmap loadBitmap(Context mContext, Uri uri, int width, int height) {
   Bitmap mBitmap = null;
   try {
     ContentResolver resolver = mContext.getContentResolver();
     BitmapFactory.Options options = new BitmapFactory.Options();
     options.inPreferredConfig = Bitmap.Config.RGB_565; // FaceDetecor只能读取RGB 565格式的Bitmap
     Bitmap bitmap = BitmapFactory.decodeStream(resolver.openInputStream(uri), null, options);
     mBitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height); // 缩放位图到指定大小
   } catch (Exception ex) {
     Log.e(mContext.getPackageName(), "图像加载异常: " + ex.getMessage());
   }
   return mBitmap;
 }
 @Test
 public void testLocalVideoMicroThumbnailReturnsNull() throws Exception {
   when(mProducerListener.requiresExtraMap(mRequestId)).thenReturn(true);
   when(android.media.ThumbnailUtils.createVideoThumbnail(
           mFile.getPath(), MediaStore.Images.Thumbnails.MICRO_KIND))
       .thenReturn(null);
   mLocalVideoThumbnailProducer.produceResults(mConsumer, mProducerContext);
   mExecutor.runUntilIdle();
   verify(mConsumer).onNewResult(null, true);
   verify(mProducerListener).onProducerStart(mRequestId, PRODUCER_NAME);
   Map<String, String> thumbnailNotFoundMap =
       ImmutableMap.of(LocalVideoThumbnailProducer.CREATED_THUMBNAIL, "false");
   verify(mProducerListener)
       .onProducerFinishWithSuccess(mRequestId, PRODUCER_NAME, thumbnailNotFoundMap);
 }
Пример #29
0
  public static Uri savePicture(Context context, Bitmap bitmap) {
    // TODO 이미지 URI변경시점 ->CAMERA액티비티에서 URI를 넘겨받음.
    int cropHeight;
    if (bitmap.getHeight() > bitmap.getWidth()) cropHeight = bitmap.getWidth();
    else cropHeight = bitmap.getHeight();

    bitmap =
        ThumbnailUtils.extractThumbnail(
            bitmap, cropHeight, cropHeight, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);

    File mediaStorageDir =
        new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            context.getString(R.string.squarecamera__app_name));

    if (!mediaStorageDir.exists()) {
      if (!mediaStorageDir.mkdirs()) {
        return null;
      }
    }

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile =
        new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");

    // Saving the bitmap
    try {
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

      FileOutputStream stream = new FileOutputStream(mediaFile);
      stream.write(out.toByteArray());
      stream.close();

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

    // Mediascanner need to scan for the image saved
    Intent mediaScannerIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri fileContentUri = Uri.fromFile(mediaFile);
    mediaScannerIntent.setData(fileContentUri);
    context.sendBroadcast(mediaScannerIntent);

    return fileContentUri;
  }
  public View getView(int position, View view, ViewGroup viewGroup) {
    if (view == null) {
      LayoutInflater inflater = ((Activity) context).getLayoutInflater();
      view = inflater.inflate(resource, viewGroup, false);
    }

    Lampiran lampiran = listOfLampiran.get(position);

    ImageView imageLampiran = (ImageView) view.findViewById(R.id.ImageViewLampiran);
    TextView textViewCaption = (TextView) view.findViewById(R.id.TextViewCaption);

    String fileNamaLampiran =
        lampiran
            .getImage()
            .substring(lampiran.getImage().lastIndexOf(".") + 1, lampiran.getImage().length());

    if (fileNamaLampiran.equals("jpg")
        || fileNamaLampiran.equals("png")
        || fileNamaLampiran.equals("gif")) {
      try {
        imageLampiran.setImageBitmap(
            GlobalFunction.decodeSampledBitmapFromFile(lampiran.getImage(), 50, 50));
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      }
    } else if (fileNamaLampiran.equals("avi")
        || fileNamaLampiran.equals("mp4")
        || fileNamaLampiran.equals("flv")
        || fileNamaLampiran.equals("mkv")
        || fileNamaLampiran.equals("3gp")) {
      Bitmap fileLampiran =
          ThumbnailUtils.createVideoThumbnail(
              lampiran.getImage(), MediaStore.Images.Thumbnails.MINI_KIND);

      imageLampiran.setImageBitmap(fileLampiran);
    } else {
      Toast.makeText(
              context, "Maaf Format Lampiran Yang Anda Pilih Tidak Sesuai", Toast.LENGTH_SHORT)
          .show();
    }

    textViewCaption.setText(lampiran.getJudul());

    return view;
  }