@SuppressWarnings("unused")
  public Bitmap getThumbnail(Uri uri, int THUMBNAIL_SIZE)
      throws FileNotFoundException, IOException {
    InputStream input = context.getContentResolver().openInputStream(uri);

    BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
    onlyBoundsOptions.inJustDecodeBounds = true;
    onlyBoundsOptions.inDither = true; // optional
    onlyBoundsOptions.inPreferredConfig = Config.ARGB_8888; // optional
    BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
    input.close();
    if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1)) return null;
    int originalSize =
        (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth)
            ? onlyBoundsOptions.outHeight
            : onlyBoundsOptions.outWidth;
    double ratio = (originalSize > THUMBNAIL_SIZE) ? (originalSize / THUMBNAIL_SIZE) : 1.0;
    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
    bitmapOptions.inDither = true; // optional
    bitmapOptions.inPreferredConfig = Config.ARGB_8888; // optional
    input = context.getContentResolver().openInputStream(uri);
    Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    input.close();
    return bitmap;
  }
예제 #2
0
  static {
    // for the cache,
    // 565 is faster to decode and display
    // and we don't want to dither here because the image will be scaled down later
    sBitmapOptionsCache.inPreferredConfig = Bitmap.Config.RGB_565;
    sBitmapOptionsCache.inDither = false;

    sBitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
    sBitmapOptions.inDither = false;
  }
예제 #3
0
  /**
   * Make a bitmap from a given Uri, minimal side length, and maximum number of pixels. The image
   * data will be read from specified pfd if it's not null, otherwise a new input stream will be
   * created using specified ContentResolver.
   *
   * <p>Clients are allowed to pass their own BitmapFactory.Options used for bitmap decoding. A new
   * BitmapFactory.Options will be created if options is null.
   */
  private static Bitmap makeBitmap(
      int minSideLength,
      int maxNumOfPixels,
      Uri uri,
      ContentResolver cr,
      ParcelFileDescriptor pfd,
      BitmapFactory.Options options) {
    Bitmap b = null;
    try {
      if (pfd == null) pfd = makeInputStream(uri, cr);
      if (pfd == null) return null;
      if (options == null) options = new BitmapFactory.Options();

      FileDescriptor fd = pfd.getFileDescriptor();
      options.inSampleSize = 1;
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeFileDescriptor(fd, null, options);
      if (options.mCancel || options.outWidth == -1 || options.outHeight == -1) {
        return null;
      }
      options.inSampleSize = computeSampleSize(options, minSideLength, maxNumOfPixels);
      options.inJustDecodeBounds = false;

      options.inDither = false;
      options.inPreferredConfig = Bitmap.Config.ARGB_8888;
      b = BitmapFactory.decodeFileDescriptor(fd, null, options);
    } catch (OutOfMemoryError ex) {
      Log.e(TAG, "Got oom exception ", ex);
      return null;
    } finally {
      closeSilently(pfd);
    }
    return b;
  }
예제 #4
0
  public MediaStoreImage(Context context, String url) {
    mContext = context;
    mId = Long.parseLong(url.substring(PREFIX.length()));

    sBitmapOptionsCache.inPreferredConfig = Bitmap.Config.RGB_565;
    sBitmapOptionsCache.inDither = false;
  }
예제 #5
0
 /**
  * Retrieve a dithered bitmap that can be used for comparison on any density
  *
  * @param resources
  * @param config the preferred config for the returning bitmap
  * @return the {@link Bitmap} or <code>null</code>
  */
 public static Bitmap getUnscaledAndDitheredBitmap(
     Resources resources, int resId, Bitmap.Config config) {
   BitmapFactory.Options options = new BitmapFactory.Options();
   options.inDither = true;
   options.inScaled = false;
   options.inPreferredConfig = config;
   return BitmapFactory.decodeResource(resources, resId, options);
 }
 /**
  * Actually converts the given {@link InputStream} into an Android {@link Bitmap}.
  *
  * <p>The hereby implementation does not perform any scaling.
  *
  * @param inputStream the representation of the {@link Bitmap} to be decoded
  * @return the decoded {@link Bitmap} if the conversion could be performed properly ; {@code
  *     null} otherwise
  * @see #convert(InputStream, String, Object, String)
  */
 protected Bitmap convertInputStreamToBitmap(
     InputStream inputStream, String bitmapUid, Object imageSpecs, String url) {
   final BitmapFactory.Options options = new BitmapFactory.Options();
   options.inScaled = false;
   options.inDither = false;
   options.inDensity = 0;
   return BitmapFactory.decodeStream(inputStream, null, options);
 }
예제 #7
0
 private Bitmap decodeBitmap(InputStream is) {
   BitmapFactory.Options options = new BitmapFactory.Options();
   options.inDither = true;
   // Prefer the bitmap config we computed from the window parameter
   options.inPreferredConfig = graphics.preferredBitmapConfig;
   // Never scale bitmaps based on device parameters
   options.inScaled = false;
   return BitmapFactory.decodeStream(is, null, options);
 }
예제 #8
0
 private static BitmapFactory.Options getOptions() {
   // Android specific options
   final BitmapFactory.Options options = new BitmapFactory.Options();
   options.inDither = true;
   options.inPurgeable = true;
   options.inTempStorage = mTempStorage;
   // Probably not used as ARGB_8888 has already been set
   options.inPreferredConfig = Config.RGB_565;
   return options;
 }
예제 #9
0
  public Jpeg(Activity a, String in_file_name, int quality, String out_file_name) {
    if (!root_dir.exists()) root_dir.mkdir();

    this.a = a;
    String string = new String();
    inFile = new File(in_file_name);

    if (in_file_name.endsWith(".jpg")
        && !in_file_name.endsWith(".tif")
        && !in_file_name.endsWith(".gif")) {
      StandardUsage();
    }

    if (out_file_name == null) {
      string = inFile.getName().substring(0, inFile.getName().lastIndexOf(".")) + ".jpg";
    } else {
      string = out_file_name;
      if (string.endsWith(".tif") || string.endsWith(".gif")) {
        string = string.substring(0, string.lastIndexOf("."));
      }

      if (!string.endsWith(".jpg")) {
        string = string.concat(".jpg");
      }
    }

    outFile = new File(root_dir, string);

    if (inFile.exists()) {
      try {
        dataOut = new FileOutputStream(outFile);
      } catch (final IOException e) {
        Log.e(LOG, e.toString());
        e.printStackTrace();
      }
      Quality = quality;

      opts = new BitmapFactory.Options();
      opts.inDither = false;
      opts.inPurgeable = true;
      opts.inInputShareable = true;
      opts.inTempStorage = new byte[32 * 1024];

      // image = BitmapFactory.decodeFile(in_file_name, opts);
      image = BitmapFactory.decodeFile(in_file_name);
      jpg = new JpegEncoder(image, Quality, dataOut, "");

    } else {
      // TODO: could not find the in file-- throw error
      Log.e(LOG, "could not find the inFile? (" + inFile.getAbsolutePath() + ")");
      return;
    }
  }
예제 #10
0
 private Bitmap getThumbnail(long id) {
   Bitmap bitmap = null;
   BitmapFactory.Options options = new BitmapFactory.Options();
   options.inDither = false;
   options.inPreferredConfig = Bitmap.Config.ARGB_8888;
   options.inScaled = true;
   options.inJustDecodeBounds = false;
   options.inPurgeable = true;
   options.inInputShareable = true;
   ContentResolver cr = mContext.getContentResolver();
   bitmap = MediaStore.Video.Thumbnails.getThumbnail(cr, id, Images.Thumbnails.MINI_KIND, null);
   return bitmap;
 }
예제 #11
0
    @Override
    protected Boolean doInBackground(Void... params) {
      // QRCodeClient client = new QRCodeClient();
      // For scanning a file from /res folder
      // InputStream fileInputStream =
      // getResources().openRawResource(R.drawable.qr_code_test_p);
      BitmapFactory.Options bfOptions = new BitmapFactory.Options();
      bfOptions.inDither = false; // Disable Dithering mode
      bfOptions.inPurgeable = true; // Tell to gc that whether it needs
      // free memory, the Bitmap can be
      // cleared
      bfOptions.inInputShareable = true; // Which kind of reference will
      // be used to recover the Bitmap
      // data after being clear, when
      // it will be used in the future
      bfOptions.inTempStorage = new byte[32 * 1024];

      Bitmap bMap = BitmapFactory.decodeFile(path, bfOptions);
      bMap = Bitmap.createScaledBitmap(bMap, 1200, 900, false); // Lets
      // change
      // size
      // to a
      // bit
      // smaller,
      // I
      // didn't
      // experiment
      // a lot
      // with
      // it so
      // it
      // can
      // be
      // not
      // optimal
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      bMap.compress(CompressFormat.PNG, 0, bos);
      byte[] bitmapdata = bos.toByteArray();
      ByteArrayInputStream fileInputStream = new ByteArrayInputStream(bitmapdata);

      BufferedInputStream bis = new BufferedInputStream(fileInputStream);
      try {
        // content = client.decode(bis);
      } catch (Exception e) {
        e.printStackTrace();
      }
      SimpleDateFormat sdf = new SimpleDateFormat("HH:mm   dd.MM", java.util.Locale.getDefault());
      Date dt = new Date();
      date = sdf.format(dt);
      return true;
    }
  public Bitmap decodeThumbFile(String path) {
    Bitmap bmp = null;
    Log.v("File Path", path);
    File f = new File(path);
    try {
      // Decode image size
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inTempStorage = new byte[16 * 1024];
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeStream(new FileInputStream(f), null, options);
      int IMAGE_MAX_SIZE = 640;
      int scale = 1;
      if (options.outHeight > IMAGE_MAX_SIZE || options.outWidth > IMAGE_MAX_SIZE) {
        scale =
            (int)
                Math.pow(
                    2,
                    (int)
                        Math.round(
                            Math.log(
                                    IMAGE_MAX_SIZE
                                        / (double) Math.max(options.outHeight, options.outWidth))
                                / Math.log(0.5)));
      }
      // Decode with inSampleSize
      BitmapFactory.Options o2 = new BitmapFactory.Options();
      o2.inSampleSize = scale;
      o2.inPurgeable = true;
      o2.outHeight = 480;
      o2.outWidth = 640;

      Bitmap temp = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      temp.compress(
          Bitmap.CompressFormat.PNG,
          (int) (100 * ImageFileManipulation.IAMGE_COMPRESSION_RATIO),
          baos);
      temp.recycle();
      temp = null;
      options = new BitmapFactory.Options();
      options.inDither = true;
      options.inPurgeable = true;
      options.inInputShareable = true;
      options.inSampleSize = scale;
      options.inTempStorage = new byte[32 * 1024];
      bmp = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.size(), options);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return bmp;
  }
  public Bitmap decodeBitmapFromPath(String filePath) {
    Bitmap scaledBitmap = null;

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    scaledBitmap = BitmapFactory.decodeFile(filePath, options);

    options.inSampleSize =
        calculateInSampleSize(options, convertDipToPixels(150), convertDipToPixels(200));
    options.inDither = false;
    options.inPurgeable = true;
    options.inInputShareable = true;
    options.inJustDecodeBounds = false;

    scaledBitmap = BitmapFactory.decodeFile(filePath, options);
    return scaledBitmap;
  }
  /** get videos form {@link MediaStore.Video.Media.EXTERNAL_CONTENT_URI} */
  public List<MediaInfo> getVideoInfo() {
    List<MediaInfo> list = new ArrayList<MediaInfo>();
    ContentResolver contentResolver = context.getContentResolver();
    Cursor cursor =
        contentResolver.query(
            DreamConstant.VIDEO_URI, null, null, null, MediaStore.Video.Media.DEFAULT_SORT_ORDER);

    if (null == cursor) {

    } else {
      if (cursor.moveToFirst()) {
        MediaInfo mediaInfo = null;
        do {
          mediaInfo = new MediaInfo();
          long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media._ID));
          long duration =
              cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media.DURATION)); // 时长
          long size = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media.SIZE)); // 文件大小
          String url = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA)); // 文件路径
          String displayName =
              cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME));
          if (new File(url).exists()) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inDither = false;
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            // get video thumbail
            Bitmap bitmap =
                MediaStore.Video.Thumbnails.getThumbnail(
                    contentResolver, id, Images.Thumbnails.MICRO_KIND, options);
            mediaInfo.setId(id);
            mediaInfo.setDuration(duration);
            mediaInfo.setSize(size);
            mediaInfo.setUrl(url);
            mediaInfo.setDisplayName(displayName);
            mediaInfo.setIcon(bitmap);
            list.add(mediaInfo);
          }

        } while (cursor.moveToNext());
      }
      cursor.close();
    }

    return list;
  }
예제 #15
0
 private Bitmap getBitmap() {
   BitmapFactory.Options options = new BitmapFactory.Options();
   options.inJustDecodeBounds = true; // 不加载bitmap到内存中
   BitmapFactory.decodeResource(getResources(), R.mipmap.guidepic, options);
   int outWidth = options.outWidth;
   int outHeight = options.outHeight;
   options.inDither = false;
   options.inPreferredConfig = Bitmap.Config.ARGB_8888;
   options.inSampleSize = 1;
   float width = (float) shebeiHight / (float) outHeight * outWidth;
   int imageWidth = Math.round(width);
   if (outWidth != 0 && outHeight != 0 && imageWidth != 0 && shebeiHight != 0) {
     int sampleSize = (outWidth / imageWidth + outHeight / shebeiHight) / 2;
     options.inSampleSize = sampleSize;
   }
   options.inJustDecodeBounds = false;
   dx = -(imageWidth - shebeiWidth);
   return BitmapFactory.decodeResource(getResources(), R.mipmap.guidepic, options);
 }
예제 #16
0
  public static Bitmap makeBitmap(byte[] jpegData, int maxNumOfPixels) {
    try {
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, options);
      if (options.mCancel || options.outWidth == -1 || options.outHeight == -1) {
        return null;
      }
      options.inSampleSize = computeSampleSize(options, -1, maxNumOfPixels);
      options.inJustDecodeBounds = false;

      options.inDither = false;
      options.inPreferredConfig = Bitmap.Config.ARGB_8888;
      return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, options);
    } catch (OutOfMemoryError ex) {
      Log.e(TAG, "Got oom exception ", ex);
      return null;
    }
  }
예제 #17
0
  private Bitmap getBitmapFromMemoryCache(Uri uri, Context context) {
    // TODO Auto-generated method stub
    ContentResolver cr = context.getContentResolver();
    try {
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeStream(cr.openInputStream(uri), null, options);
      options.inSampleSize = 4; // 图片宽高都为原来的二分之一,即图片为原来的四分之一
      options.inJustDecodeBounds = false;
      options.inDither = false;
      options.inPreferredConfig = Bitmap.Config.ARGB_8888;
      Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri), null, options);
      return bitmap;

    } catch (FileNotFoundException exp) {
      exp.printStackTrace();
      return null;
    }
  }
예제 #18
0
  public static Bitmap decodeBitmap(Resources res, int resId, int reqWidth, int reqHeight) {
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize (use 1024 as maximum size, the minimum supported
    // by all the gles20 devices)
    options.inSampleSize =
        calculateBitmapRatio(options, Math.min(reqWidth, 1024), Math.min(reqHeight, 1024));

    // Decode the bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    options.inPreferQualityOverSpeed = false;
    options.inPurgeable = true;
    options.inInputShareable = true;
    options.inDither = true;
    return BitmapFactory.decodeResource(res, resId, options);
  }
예제 #19
0
  /**
   * Options returned by this method are configured with mDecodeBuffer which is GuardedBy("this")
   */
  private static BitmapFactory.Options getDecodeOptionsForStream(
      EncodedImage encodedImage, Bitmap.Config bitmapConfig) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    // Sample size should ONLY be different than 1 when downsampling is enabled in the pipeline
    options.inSampleSize = encodedImage.getSampleSize();
    options.inJustDecodeBounds = true;
    // fill outWidth and outHeight
    BitmapFactory.decodeStream(encodedImage.getInputStream(), null, options);
    if (options.outWidth == -1 || options.outHeight == -1) {
      throw new IllegalArgumentException();
    }

    options.inJustDecodeBounds = false;
    options.inDither = true;
    options.inPreferredConfig = bitmapConfig;
    options.inMutable = true;

    return options;
  }
예제 #20
0
    @Override
    protected void onProgressUpdate(String... values) {
      File file = new File(values[0]);
      if (file.getName().toLowerCase().endsWith(".jpg")
          || file.getName().toLowerCase().endsWith(".png")
          || file.getName().toLowerCase().endsWith(".gif")
          || file.getName().toLowerCase().endsWith(".jpeg")) {
        if (myBitmap != null) {
          myBitmap = null;
        }
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inDither = false;
        opts.inTempStorage = new byte[1024 * 1024];
        myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), opts);
        video.setVisibility(View.INVISIBLE);
        imagem.setVisibility(View.VISIBLE);

        // imagem.setImageBitmap(myBitmap);
        imagem.post(
            new Runnable() {
              @Override
              public void run() {
                imagem.setImageBitmap(myBitmap);
              }
            });

      } else if (file.getName().toLowerCase().endsWith(".avi")
          || file.getName().toLowerCase().endsWith(".mp4")
          || file.getName().toLowerCase().endsWith(".mpeg")) {
        video.setVisibility(View.VISIBLE);
        imagem.setVisibility(View.INVISIBLE);
        video.setVideoPath(file.getAbsolutePath());
        video.setOnPreparedListener(
            new MediaPlayer.OnPreparedListener() {
              @Override
              public void onPrepared(MediaPlayer mp) {
                video.start();
                duracao = video.getDuration();
              }
            });
      }
    }
예제 #21
0
 /**
  * Make bitmap.
  *
  * @param minSideLength the min side length
  * @param maxNumOfPixels the max num of pixels
  * @param uri the uri
  * @param cr the cr
  * @param pfd the pfd
  * @param options the options
  * @return the bitmap
  */
 private Bitmap makeBitmap(
     int minSideLength,
     int maxNumOfPixels,
     Uri uri,
     ContentResolver cr,
     ParcelFileDescriptor pfd,
     final BitmapFactory.Options options) {
   Logger.v(TAG, "makeBitmap entry");
   if (pfd == null) {
     Logger.d(TAG, "makeBitmap pfd is null");
     return null;
   }
   try {
     BitmapFactory.Options tempOptions = options;
     if (tempOptions == null) {
       tempOptions = new BitmapFactory.Options();
     }
     FileDescriptor fd = pfd.getFileDescriptor();
     tempOptions.inJustDecodeBounds = true;
     BitmapFactory.decodeFileDescriptor(fd, null, tempOptions);
     if (tempOptions.mCancel || tempOptions.outWidth == -1 || tempOptions.outHeight == -1) {
       return null;
     }
     tempOptions.inSampleSize = computeSampleSize(tempOptions, minSideLength, maxNumOfPixels);
     tempOptions.inJustDecodeBounds = false;
     // for zoom pan performance enhancement,
     // load full size bitmap in format RGB_565, with dither option
     // on
     tempOptions.inDither = false;
     tempOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
     // options.inDither = true;
     // options.inPreferredConfig = Bitmap.Config.RGB_565;
     Logger.v(TAG, "makeBitmap exit");
     return BitmapFactory.decodeFileDescriptor(fd, null, tempOptions);
   } catch (OutOfMemoryError ex) {
     Logger.e(TAG, "got oom exception");
     ex.printStackTrace();
     return null;
   } finally {
     closeSilently(pfd);
   }
 }
예제 #22
0
 private Bitmap makeBitmap(byte[] jpegData) {
   try {
     if (jpegData != null && jpegData.length > 0) {
       BitmapFactory.Options options = new BitmapFactory.Options();
       options.inJustDecodeBounds = true;
       BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, options);
       if (options.mCancel || options.outWidth == -1 || options.outHeight == -1) {
         return null;
       }
       options.inJustDecodeBounds = false;
       options.inDither = false;
       options.inPurgeable = true;
       options.inPreferredConfig = Bitmap.Config.ARGB_8888;
       return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, options);
     }
   } catch (OutOfMemoryError ex) {
     ex.printStackTrace();
   }
   return null;
 }
예제 #23
0
  /**
   * * reset width,height option for Bitmap
   *
   * @param file
   * @param width
   * @param height
   * @return
   */
  private static BitmapFactory.Options setBitmapoption(String file, int width, int height) {

    BitmapFactory.Options option = new BitmapFactory.Options();
    // flag for just decode bounds
    option.inJustDecodeBounds = true;

    BitmapFactory.decodeFile(file, option);
    int outWidth = option.outWidth;
    int outHeight = option.outHeight;
    option.inDither = false; // dont do 24 to 16
    option.inPreferredConfig = Bitmap.Config.RGB_565;
    option.inSampleSize = 1;
    if (outWidth != 0 && outHeight != 0 && width != 0 && height != 0) {
      int sampleSize = (outWidth / width + outHeight / height) / 2;
      option.inSampleSize = sampleSize;
    }

    option.inJustDecodeBounds = false;
    return option;
  }
  /**
   * 从文件当中获取专辑封面位图
   *
   * @param context
   * @param songid
   * @param albumid
   * @return
   */
  public static Bitmap getArtworkFromFile(Context context, long songid, long albumid) {
    Bitmap bm = null;
    if (albumid < 0 && songid < 0) {
      throw new IllegalArgumentException("Must specify an album or a song id");
    }
    try {
      BitmapFactory.Options options = new BitmapFactory.Options();
      FileDescriptor fd = null;
      if (albumid < 0) {
        Uri uri = Uri.parse("content://media/external/audio/media/" + songid + "/albumart");
        ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
        if (pfd != null) {
          fd = pfd.getFileDescriptor();
        }
      } else {
        Uri uri = ContentUris.withAppendedId(albumArtUri, albumid);
        ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
        if (pfd != null) {
          fd = pfd.getFileDescriptor();
        }
      }
      options.inSampleSize = 1;
      // 只进行大小判断
      options.inJustDecodeBounds = true;
      // 调用此方法得到options得到图片大小
      BitmapFactory.decodeFileDescriptor(fd, null, options);
      // 我们的目标是在800pixel的画面上显示
      // 所以需要调用computeSampleSize得到图片缩放的比例
      options.inSampleSize = 100;
      // 我们得到了缩放的比例,现在开始正式读入Bitmap数据
      options.inJustDecodeBounds = false;
      options.inDither = false;
      options.inPreferredConfig = Bitmap.Config.ARGB_8888;

      // 根据options参数,减少所需要的内存
      bm = BitmapFactory.decodeFileDescriptor(fd, null, options);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    return bm;
  }
예제 #25
0
  /**
   * Decodes a sampled Bitmap from the provided url in the requested width and height
   *
   * @param urlString URL to download the bitmap from
   * @param reqWidth Requested width
   * @param reqHeight Requested height
   * @return Decoded bitmap
   */
  public Bitmap decodeSampledBitmapFromUrl(final String urlString, int reqWidth, int reqHeight) {
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    options.inPurgeable = true;
    options.inDither = false;
    options.inInputShareable = true;

    final BitmapConnection bitmapConnection = new BitmapConnection();
    bitmapConnection.readStream(
        urlString,
        new BitmapConnection.Runnable<Void>() {
          @Override
          public Void run(final InputStream stream) {
            decodeStream(stream, options);
            return null;
          }
        });

    if (reqWidth == 0) {
      reqWidth = options.outWidth;
    }
    if (reqHeight == 0) {
      reqHeight = options.outHeight;
    }

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    return bitmapConnection.readStream(
        urlString,
        new BitmapConnection.Runnable<Bitmap>() {
          @Override
          public Bitmap run(final InputStream stream) {
            return decodeStream(stream, options);
          }
        });
  }
 /** @return Bitmap or null... */
 private static Bitmap getCustomResourceSampled(
     final Context context, final int resourceID, final int reqWidth, final int reqHeight) {
   final BitmapFactory.Options options = new BitmapFactory.Options();
   options.inPreferredConfig = Bitmap.Config.ARGB_8888;
   options.inDither = false; // Disable Dithering mode
   options.inPurgeable = true; // Tell to gc that whether it needs free
   // memory, the Bitmap can be cleared
   options.inInputShareable = true; // Which kind of reference will be
   // used to recover the Bitmap
   // data after being clear, when
   // it will be used in the future
   options.inTempStorage = new byte[32 * 1024];
   options.inJustDecodeBounds = true;
   BitmapFactory.decodeResource(context.getResources(), resourceID, options);
   // Calculate inSampleSize
   options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
   // Decode bitmap with inSampleSize set
   options.inJustDecodeBounds = false;
   final Bitmap b = BitmapFactory.decodeResource(context.getResources(), resourceID, options);
   return b;
 }
예제 #27
0
  private void initComponents() {
    this.sv = (SurfaceView) this.findViewById(R.id.playSurface);
    this.sh = sv.getHolder();
    this.frameBar = (SeekBar) this.findViewById(R.id.frameBar);
    this.loadingText = (TextView) this.findViewById(R.id.loadingText);
    this.frameText = (TextView) this.findViewById(R.id.frameText);
    this.nameTitle = (TextView) this.findViewById(R.id.nameTitle);
    this.ctrlView = this.findViewById(R.id.ctrlView);
    this.touchPlayView = this.findViewById(R.id.touchPlayView);

    this.touchPlayView.setOnClickListener(playStopListener);
    this.frameBar.setOnSeekBarChangeListener(playFrameListener);

    this.ctrlView.setVisibility(View.GONE);
    this.loadingText.setVisibility(View.GONE);

    this.bmpOptions = new BitmapFactory.Options();
    bmpOptions.inPurgeable = true;
    bmpOptions.inDither = false;
    bmpOptions.inInputShareable = true;
  }
  @Override
  protected void toJSON(UserSettings user, JSONObject object) throws JSONException {

    String encoded = null;

    try {
      if (user.getImage() != null) {
        encoded = bitmapUtils.encode(user.getImage());
      } else if (user.getLocalImagePath() != null) {

        BitmapFactory.Options bfo = new BitmapFactory.Options();
        bfo.inDither = true;
        bfo.inSampleSize = 4;

        Bitmap bm = BitmapFactory.decodeFile(user.getLocalImagePath(), bfo);

        encoded = bitmapUtils.encode(bm);

        bm.recycle();

        user.setLocalImagePath(null);
      }
    } catch (Throwable e) {
      // TODO: Handle OOM errors by changing sample size on profile images
      e.printStackTrace();
    }

    object.put(FIRST_NAME, user.getFirstName());
    object.put(LAST_NAME, user.getLastName());

    if (encoded != null) {
      object.put(IMAGE_DATA, encoded);
    }

    object.put(AUTO_POST_FACEBOOK, user.isAutoPostFacebook());
    object.put(AUTO_POST_TWITTER, user.isAutoPostTwitter());
    object.put(SHARE_LOCATION, user.isLocationEnabled());
    object.put(NOTIFICATIONS_ENABLED, user.isNotificationsEnabled());
    object.put(SHOW_AUTH, user.isShowAuthDialog());
  }
예제 #29
0
  /**
   * Out of Memory hack taken from here http://stackoverflow.com/a/7116158/527759
   *
   * @param path
   * @return
   */
  Bitmap getBitmap(String path) {
    Bitmap bm = null;
    BitmapFactory.Options bfOptions = new BitmapFactory.Options();
    bfOptions.inDither = false; // Disable Dithering mode
    bfOptions.inPurgeable = true; // Tell to gc that whether it needs
    // free memory, the Bitmap can be
    // cleared
    bfOptions.inInputShareable = true; // Which kind of reference will
    // be used to recover the Bitmap
    // data after being clear, when
    // it will be used in the future
    bfOptions.inTempStorage = new byte[32 * 1024];

    File file = new File(path);
    FileInputStream fs = null;
    try {
      fs = new FileInputStream(file);
    } catch (FileNotFoundException e) {
      // TODO do something intelligent
      e.printStackTrace();
    }

    try {
      if (fs != null) bm = BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
    } catch (IOException e) {
      // GuiUtils.error(TAG, null, e);
    } finally {
      if (fs != null) {
        try {
          fs.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return bm;
  }
 /** @return Bitmap or null... */
 public static Bitmap getCustomImageSampled(
     final String filePath, final int reqWidth, final int reqHeight) {
   if (!filePath.equals("aaa")) {
     final BitmapFactory.Options options = new BitmapFactory.Options();
     options.inPreferredConfig = Bitmap.Config.ARGB_8888;
     options.inDither = false; // Disable Dithering mode
     options.inPurgeable = true; // Tell to gc that whether it needs free
     // memory, the Bitmap can be cleared
     options.inInputShareable = true; // Which kind of reference will be
     // used to recover the Bitmap
     // data after being clear, when
     // it will be used in the future
     options.inTempStorage = new byte[32 * 1024];
     options.inJustDecodeBounds = true;
     BitmapFactory.decodeFile(filePath, options);
     // Calculate inSampleSize
     options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
     // Decode bitmap with inSampleSize set
     options.inJustDecodeBounds = false;
     final Bitmap b = BitmapFactory.decodeFile(filePath, options);
     return b;
   }
   return null;
 }