예제 #1
1
  public static void resizeRotateAndSaveByteArrayToSDCardPath(
      String desiredName, byte[] data, float targetWidth, float targetHeight) {
    /** GET bitmap info * */
    BitmapFactory.Options opts = new Options();
    opts.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(data, 0, data.length, opts);

    /** scale approximately * */
    opts.inJustDecodeBounds = false;
    opts.inSampleSize =
        calculateInSampleSize(opts, Math.round(targetWidth), Math.round(targetHeight));
    Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
    data = null;

    /** calculate final WIDTH and HEIGHT (with right aspect ratio) * */
    int originalWidth = bmp.getWidth();
    int originalHeight = bmp.getHeight();
    float scale = (float) targetWidth / (float) originalWidth;
    int newWidth = Math.round(targetWidth);
    int newHeight = Math.round(scale * (float) originalHeight);

    /** resize exactly to desired size * */
    Bitmap scaledBmp = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true);
    /** rotating * */
    Matrix mtx = new Matrix();
    mtx.preRotate(90);
    /** saving * */
    saveToSDCardPath(
        desiredName,
        Bitmap.createBitmap(
            scaledBmp, 0, 0, scaledBmp.getWidth(), scaledBmp.getHeight(), mtx, true));
  }
예제 #2
0
 // if null so erreur
 public ArrayList<ArticleModel> getListModel(ArrayList<Article> listes, Context context) {
   ArrayList<ArticleModel> listeModel = new ArrayList<>();
   try {
     for (int i = 0; i < listes.size(); i++) {
       File file = context.getFileStreamPath(listes.get(i).getIdArticle() + ".png");
       if (file.exists()) {
         Bitmap bitmap = null;
         BitmapFactory.Options options = new BitmapFactory.Options();
         options.inPreferredConfig = Bitmap.Config.ARGB_8888;
         try {
           bitmap = BitmapFactory.decodeStream(new FileInputStream(file), null, options);
           listeModel.add(
               new ArticleModel(
                   bitmap, listes.get(i).getTitleArticle(), listes.get(i).getContentArticle()));
         } catch (FileNotFoundException e) {
           e.printStackTrace();
         }
       }
     }
     return listeModel;
   } catch (Exception e) {
     e.printStackTrace();
   }
   return null;
 }
 /**
  * 获取指定路径下的图片的指定大小的缩略图 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;
 }
예제 #4
0
  // decodes image and scales it to reduce memory consumption
  private Bitmap decodeFile(File f) {
    try {
      // decode image size
      BitmapFactory.Options o = new BitmapFactory.Options();
      o.inJustDecodeBounds = true;
      FileInputStream stream1 = new FileInputStream(f);
      BitmapFactory.decodeStream(stream1, null, o);
      stream1.close();

      // Find the correct scale value. It should be the power of 2.
      final int REQUIRED_SIZE = 70;
      int width_tmp = o.outWidth, height_tmp = o.outHeight;
      int scale = 1;
      while (true) {
        if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
      }

      // decode with inSampleSize
      BitmapFactory.Options o2 = new BitmapFactory.Options();
      o2.inSampleSize = scale;
      FileInputStream stream2 = new FileInputStream(f);
      Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
      stream2.close();
      return bitmap;
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
  /**
   * Create a bitmap from a local URI
   *
   * @param resolver The ContentResolver
   * @param uri The local URI
   * @param maxSize The maximum size (either width or height)
   * @return The new bitmap or null
   */
  public static BitmapResult createLocalBitmap(
      final ContentResolver resolver, final Uri uri, final int maxSize) {
    final BitmapResult result = new BitmapResult();
    final InputStreamFactory factory = createInputStreamFactory(resolver, uri);
    try {
      final Point bounds = getImageBounds(factory);
      if (bounds == null) {
        result.status = BitmapResult.STATUS_EXCEPTION;
        return result;
      }

      final BitmapFactory.Options opts = new BitmapFactory.Options();
      opts.inSampleSize = Math.max(bounds.x / maxSize, bounds.y / maxSize);
      result.bitmap = decodeStream(factory, null, opts);
      result.status = BitmapResult.STATUS_SUCCESS;
      return result;

    } catch (FileNotFoundException exception) {
      // Do nothing - the photo will appear to be missing
    } catch (IOException exception) {
      result.status = BitmapResult.STATUS_EXCEPTION;
    } catch (IllegalArgumentException exception) {
      // Do nothing - the photo will appear to be missing
    } catch (SecurityException exception) {
      result.status = BitmapResult.STATUS_EXCEPTION;
    }
    return result;
  }
예제 #6
0
  /**
   * <图片按比例大小压缩方法(根据路径获取图片并压缩)>
   *
   * @return 压缩后图片路径
   */
  public static String getImageScaleByPath(PicturePropertiesBean propertiesBean, Context context) {
    Bitmap bitmap = null;
    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
    newOpts.inJustDecodeBounds = true;
    bitmap = BitmapFactory.decodeFile(propertiesBean.getSrcPath(), newOpts);
    int width = newOpts.outWidth;
    int height = newOpts.outHeight;
    //        float minHeight = 800f;//设置为主流手机分辨率800*480

    // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
    int be = 1; // be=1表示不缩放
    if (height > width && width > propertiesBean.getWidth()) {
      // 如果宽度大的话根据宽度固定大小缩放
      be = (int) (newOpts.outWidth / propertiesBean.getWidth());
    } else if (width > height && height > propertiesBean.getHeight()) {
      // 如果高度高的话根据宽度固定大小缩放
      be = (int) (newOpts.outHeight / propertiesBean.getHeight());
    }
    if (be <= 0) be = 1;
    newOpts.inSampleSize = be; // 设置缩放比例
    newOpts.inJustDecodeBounds = false;
    bitmap = BitmapFactory.decodeFile(propertiesBean.getSrcPath(), newOpts);
    return compressImage(bitmap, context, propertiesBean); // 压缩好比例大小后再进行质量压缩
  }
예제 #7
0
  /**
   * Decode and sample down a bitmap from a file to the requested width and height.
   *
   * @param filename The full path of the file to decode
   * @param reqWidth The requested width of the resulting bitmap
   * @param reqHeight The requested height of the resulting bitmap
   * @param cache The ImageCache used to find candidate bitmaps for use with inBitmap
   * @return A bitmap sampled down from the original with the same aspect ratio and dimensions that
   *     are equal to or greater than the requested width and height
   */
  public static Bitmap decodeSampledBitmapFromUri(
      Context context, Uri fileuri, int reqWidth, int reqHeight, ImageCache cache) {

    Bitmap bm = null;

    try {
      // First decode with inJustDecodeBounds=true to check dimensions
      final BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeStream(
          context.getContentResolver().openInputStream(fileuri), null, options);

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

      // Decode bitmap with inSampleSize set
      options.inJustDecodeBounds = false;
      bm =
          BitmapFactory.decodeStream(
              context.getContentResolver().openInputStream(fileuri), null, options);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

    return bm;
  }
예제 #8
0
  public DessertCaseView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    final Resources res = getResources();

    mStarted = false;

    mCellSize = res.getDimensionPixelSize(R.dimen.dessert_case_cell_size);
    final BitmapFactory.Options opts = new BitmapFactory.Options();
    if (mCellSize < 512) { // assuming 512x512 images
      opts.inSampleSize = 2;
    }
    opts.inMutable = true;
    Bitmap loaded = null;
    for (int[] list : new int[][] {PASTRIES, RARE_PASTRIES, XRARE_PASTRIES, XXRARE_PASTRIES}) {
      for (int resid : list) {
        opts.inBitmap = loaded;
        loaded = BitmapFactory.decodeResource(res, resid, opts);
        final BitmapDrawable d = new BitmapDrawable(res, convertToAlphaMask(loaded));
        d.setColorFilter(new ColorMatrixColorFilter(ALPHA_MASK));
        d.setBounds(0, 0, mCellSize, mCellSize);
        mDrawables.append(resid, d);
      }
    }
    loaded = null;
    if (DEBUG) setWillNotDraw(false);
  }
예제 #9
0
  /** Retorna um Bitmap de modo que nao utilize muita memoria. Previne o memoryOutOfBounds */
  public static Bitmap decodeFile(File f) {
    try {
      // Decode image size
      BitmapFactory.Options o = new BitmapFactory.Options();
      o.inJustDecodeBounds = true;
      BitmapFactory.decodeStream(new FileInputStream(f), null, o);

      // The new size we want to scale to
      final int REQUIRED_SIZE = 70;

      // Find the correct scale value. It should be the power of 2.
      int width_tmp = o.outWidth, height_tmp = o.outHeight;
      int scale = 1;
      while (true) {
        if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
      }

      // Decode with inSampleSize
      BitmapFactory.Options o2 = new BitmapFactory.Options();
      o2.inSampleSize = scale;
      return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException fnfe) {
      Log.e(ConstantesSistema.LOG_TAG, fnfe.getMessage() + " - " + fnfe.getCause());
    }

    return null;
  }
예제 #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
 public static final Bitmap createOptimizedBitMap(File image) {
   BitmapFactory.Options options = new BitmapFactory.Options();
   Log.i("KOBE", image.length() + "");
   options.inSampleSize = (int) (image.length() / (512 * 1024)) + 1;
   Log.i("KOBE-Size", options.inSampleSize + "");
   return BitmapFactory.decodeFile(image.getAbsolutePath(), options);
 }
예제 #12
0
  public static KrollDict createDictForImage(TiBlob imageData, String mimeType) {
    KrollDict d = new KrollDict();
    d.putCodeAndMessage(NO_ERROR, null);

    int width = -1;
    int height = -1;

    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inJustDecodeBounds = true;

    // We only need the ContentResolver so it doesn't matter if the root or current activity is used
    // for
    // accessing it
    BitmapFactory.decodeStream(imageData.getInputStream(), null, opts);

    width = opts.outWidth;
    height = opts.outHeight;

    d.put("x", 0);
    d.put("y", 0);
    d.put("width", width);
    d.put("height", height);

    KrollDict cropRect = new KrollDict();
    cropRect.put("x", 0);
    cropRect.put("y", 0);
    cropRect.put("width", width);
    cropRect.put("height", height);
    d.put("cropRect", cropRect);

    d.put("mediaType", MEDIA_TYPE_PHOTO);
    d.put("media", imageData);

    return d;
  }
 private Bitmap readFromDb(String name, Bitmap b) {
   if (mCachedSelectQuery == null) {
     mCachedSelectQuery = CacheDb.COLUMN_NAME + " = ? AND " + CacheDb.COLUMN_SIZE + " = ?";
   }
   SQLiteDatabase db = mDb.getReadableDatabase();
   Cursor result =
       db.query(
           CacheDb.TABLE_NAME,
           new String[] {CacheDb.COLUMN_PREVIEW_BITMAP}, // cols to return
           mCachedSelectQuery, // select query
           new String[] {name, mSize}, // args to select query
           null,
           null,
           null,
           null);
   if (result.getCount() > 0) {
     result.moveToFirst();
     byte[] blob = result.getBlob(0);
     result.close();
     final BitmapFactory.Options opts = mCachedBitmapFactoryOptions.get();
     opts.inBitmap = b;
     opts.inSampleSize = 1;
     try {
       return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
     } catch (IllegalArgumentException e) {
       removeItemFromDb(mDb, name);
       return null;
     }
   } else {
     result.close();
     return null;
   }
 }
  public static int getScaleFactor(String filepath, int targetW, int targetH) {

    int inSampleSize = 1;

    // Get the dimensions of the image from EXIF
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filepath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    if (photoH > targetH || photoW > targetW) {

      // Calculate ratios of height and width to requested height and width
      final int heightRatio = Math.round((float) photoH / (float) targetH);
      final int widthRatio = Math.round((float) photoW / (float) targetW);

      // Choose the smallest ratio as inSampleSize value, this will guarantee
      // a final image with both dimensions larger than or equal to the
      // requested height and width.
      inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }

    return inSampleSize;
  }
  public static final Bitmap decodeBitmap(String filePath, int targetW, int targetH) {
    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    // Determine how much to scale down the image
    int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    Bitmap src = BitmapFactory.decodeFile(filePath, bmOptions);
    Matrix matrix = getMatrixForImageOrientation(filePath);

    if (src != null) {
      return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
    }

    return null;
  }
예제 #16
0
 /**
  * 指定大小的压缩
  *
  * @param path
  * @param limtMax
  * @return
  * @throws java.io.IOException
  */
 private static Bitmap revitionImageSize(String path, int limtMax) throws IOException {
   // 取得图片
   File file = new File(path);
   InputStream temp = new FileInputStream(file);
   BitmapFactory.Options options = new BitmapFactory.Options();
   // 这个参数代表,不为bitmap分配内存空间,只记录一些该图片的信息(例如图片大小),说白了就是为了内存优化
   options.inJustDecodeBounds = true;
   // 通过创建图片的方式,取得options的内容(这里就是利用了java的地址传递来赋值)
   BitmapFactory.decodeStream(temp, null, options);
   // 关闭流
   temp.close();
   // 生成压缩的图片
   int i = 0;
   Bitmap bitmap = null;
   while (true) {
     // 这一步是根据要设置的大小,使宽和高都能满足
     if ((options.outWidth >> i <= limtMax) && (options.outHeight >> i <= limtMax)) {
       // 重新取得流,注意:这里一定要再次加载,不能二次使用之前的流!
       temp = new FileInputStream(file);
       // 这个参数表示 新生成的图片为原始图片的几分之一。
       options.inSampleSize = (int) Math.pow(2.0D, i);
       // 这里之前设置为了true,所以要改为false,否则就创建不出图片
       options.inJustDecodeBounds = false;
       options.inTargetDensity = 240;
       bitmap = BitmapFactory.decodeStream(temp, null, options);
       break;
     }
     i += 1;
   }
   return bitmap;
 }
  public String saveImage(Uri image, int width, int height) {
    String imagePath = null;
    try {

      byte[] data = readFileThroughUri(image);
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.outWidth = height;
      options.outHeight = width;
      options.inSampleSize = 2;
      Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length, options);
      Bitmap scaledBmp = Bitmap.createScaledBitmap(bmp, width, height, false);
      bmp.recycle();
      bmp = null;
      ByteArrayOutputStream bytes = new ByteArrayOutputStream();
      scaledBmp.compress(
          Bitmap.CompressFormat.JPEG,
          (int) (100 * ImageFileManipulation.IAMGE_COMPRESSION_RATIO),
          bytes);
      imagePath = ImageFileManipulation.EXTERNAL_MEMORY + getFileName() + ".jpeg";
      boolean isFileCreate = createFileInData(imagePath, bytes.toByteArray());
      if (!isFileCreate) // if file is not created return null
      return null;

    } catch (Exception e) {
      e.printStackTrace();
    }
    return imagePath;
  }
예제 #18
0
파일: MenuFrg.java 프로젝트: dipeca/rs
  private void setPic() {

    /* There isn't enough memory to open up more than a couple camera photos */
    /* So pre-scale the target bitmap into which the file is decoded */

    /* Get the size of the ImageView */
    int targetW = mImageView.getWidth();
    int targetH = mImageView.getHeight();

    /* Get the size of the image */
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    /* Figure out which way needs to be reduced less */
    int scaleFactor = 1;
    if ((targetW > 0) || (targetH > 0)) {
      scaleFactor = Math.min(photoW / targetW, photoH / targetH);
    }

    /* Set bitmap options to scale the image decode target */
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    /* Decode the JPEG file into a Bitmap */
    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);

    /* Associate the Bitmap to the ImageView */
    mImageView.setImageBitmap(bitmap);
    mImageView.setVisibility(View.VISIBLE);
  }
예제 #19
0
  public static Drawable createBlurredImageFromBitmap(
      Bitmap bitmap, Context context, int inSampleSize) {

    RenderScript rs = RenderScript.create(context);
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = inSampleSize;

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    byte[] imageInByte = stream.toByteArray();
    ByteArrayInputStream bis = new ByteArrayInputStream(imageInByte);
    Bitmap blurTemplate = BitmapFactory.decodeStream(bis, null, options);

    final android.support.v8.renderscript.Allocation input =
        android.support.v8.renderscript.Allocation.createFromBitmap(rs, blurTemplate);
    final android.support.v8.renderscript.Allocation output =
        android.support.v8.renderscript.Allocation.createTyped(rs, input.getType());
    final android.support.v8.renderscript.ScriptIntrinsicBlur script =
        android.support.v8.renderscript.ScriptIntrinsicBlur.create(
            rs, android.support.v8.renderscript.Element.U8_4(rs));
    script.setRadius(8f);
    script.setInput(input);
    script.forEach(output);
    output.copyTo(blurTemplate);
    Drawable dr = new BitmapDrawable(blurTemplate);

    return dr;
  }
예제 #20
0
  /**
   * @param is image input stream
   * @return sampling factor
   * @throws IOException if error happens
   */
  private int resolveSampleFactor(final InputStream is, final BitmapFactory.Options options)
      throws IOException {
    if (!is.markSupported()) {
      throw new IllegalStateException("Input stream does not support marks!");
    }

    options.inJustDecodeBounds = true;
    int result = 1;
    try {

      MarkableInputStream markableStream = new MarkableInputStream(is); // Thanks to Square guys :)
      long mark = markableStream.savePosition(BOUNDS_INFO_MARK);
      doStreamDecode(markableStream, options);

      result =
          ImagesManager.calculateSampleFactor(
              options.outWidth, options.outHeight, getRequiredWidth(), getRequiredHeight());

      markableStream.reset(mark);

    } finally {
      options.inJustDecodeBounds = false;
    }
    return result;
  }
예제 #21
0
 /**
  * <根据URL下载图片,并保存到本地> <功能详细描述>
  *
  * @param imageURL
  * @param context
  * @return
  * @see [类、类#方法、类#成员]
  */
 public static Bitmap loadImageFromUrl(String imageURL, File file, Context context) {
   Bitmap bitmap = null;
   try {
     URL url = new URL(imageURL);
     HttpURLConnection con = (HttpURLConnection) url.openConnection();
     con.setDoInput(true);
     con.connect();
     if (con.getResponseCode() == 200) {
       InputStream inputStream = con.getInputStream();
       FileUtil.deleteDirectory(FileSystemManager.getUserHeadPath(context, Global.getUserId()));
       ByteArrayOutputStream OutputStream = new ByteArrayOutputStream();
       FileOutputStream out = new FileOutputStream(file.getPath());
       byte buf[] = new byte[1024 * 20];
       int len = 0;
       while ((len = inputStream.read(buf)) != -1) {
         OutputStream.write(buf, 0, len);
       }
       OutputStream.flush();
       OutputStream.close();
       inputStream.close();
       out.write(OutputStream.toByteArray());
       out.close();
       BitmapFactory.Options imageOptions = new BitmapFactory.Options();
       imageOptions.inPreferredConfig = Bitmap.Config.RGB_565;
       imageOptions.inPurgeable = true;
       imageOptions.inInputShareable = true;
       bitmap = BitmapFactory.decodeFile(file.getPath(), imageOptions);
     }
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return bitmap;
 }
예제 #22
0
  public static BitmapDrawable getSmallImageFromURL(String path) throws Exception {
    if (path.equals("")) {

      return null;
    } else {
      String urlpath = sendGETRequest(path);
      URL url = new URL(urlpath);
      Bitmap bitmap;
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setConnectTimeout(5 * 1000);
      conn.setRequestMethod("GET");
      InputStream inStream;
      if (conn.getResponseCode() == 200) {
        byte[] data = readStream(conn.getInputStream());
        int a = data.length;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 4;
        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
        BitmapDrawable bd = new BitmapDrawable(bitmap);
        bitmap = null;
        return bd;
      } else {
        System.out.println("NET IS NOTVal");
      }
      return null;
    }
  }
  /**
   * Gets the image bounds
   *
   * @param factory Used to create the InputStream.
   * @return The image bounds
   */
  private static Point getImageBounds(final InputStreamFactory factory) throws IOException {
    final BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inJustDecodeBounds = true;
    decodeStream(factory, null, opts);

    return new Point(opts.outWidth, opts.outHeight);
  }
  private Bitmap handleImage(String imagePath) {
    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(imagePath, bitmapOptions);

    // set bitmap options to scale the image decode target
    bitmapOptions.inJustDecodeBounds = false;
    bitmapOptions.inSampleSize = 4;
    bitmapOptions.inPurgeable = true;

    // decode the JPEG file into a bitmap
    Bitmap originalBitmap = null;
    Bitmap bitmap = null;
    try {
      originalBitmap = BitmapFactory.decodeFile(imagePath, bitmapOptions);
      bitmap = BitmapScaler.scaleToFill(originalBitmap, mImageSize, mImageSize);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
      if (originalBitmap != null) originalBitmap.recycle();
    }

    // handle bitmap rotation
    int rotation = getBitmapRotation(imagePath);
    if (rotation > 0) {
      Matrix matrix = new Matrix();
      matrix.setRotate(rotation, (float) bitmap.getWidth() / 2, (float) bitmap.getHeight() / 2);
      bitmap =
          Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    return bitmap;
  }
예제 #25
0
  /**
   * Decode and sample down a bitmap from resources to the requested width and height.
   *
   * @param res The resources object containing the image data
   * @param resId The resource id of the image data
   * @param reqWidth The requested width of the resulting bitmap
   * @param reqHeight The requested height of the resulting bitmap
   * @param cache The ImageCache used to find candidate bitmaps for use with inBitmap
   * @return A bitmap sampled down from the original with the same aspect ratio and dimensions that
   *     are equal to or greater than the requested width and height
   */
  public static Bitmap decodeSampledBitmapFromResource(
      Resources res,
      int resId,
      int reqWidth,
      int reqHeight,
      com.qicheng.business.ui.chat.utils.video.ImageCache cache) {

    // BEGIN_INCLUDE (read_bitmap_dimensions)
    // 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
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    // END_INCLUDE (read_bitmap_dimensions)

    // If we're running on Honeycomb or newer, try to use inBitmap
    if (Utils.hasHoneycomb()) {
      addInBitmapOptions(options, cache);
    }

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
  }
예제 #26
0
 public static Bitmap getImageFromByte(byte[] bytes, int sampleSize) {
   BitmapFactory.Options options = new BitmapFactory.Options();
   options.inPreferredConfig = Bitmap.Config.RGB_565;
   options.inSampleSize = sampleSize;
   Bitmap bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
   return Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight());
 }
예제 #27
0
  /**
   * Create and returns the Bitmap image from local storage optimized by size
   *
   * @param imageID - filename of the image
   * @param reqSize - maximum side of image returns default image (DEFAULT_IMAGE_NAME) if image
   *     can't be loaded used in ArticleViewAdapter.getView()
   */
  public static Bitmap getBitmapFromStorage(Context context, String imageID, int reqSize) {
    Log.d(TAG, ".getBitmapFromFilePath(), image=" + imageID + ", size=" + reqSize);

    Bitmap result = null;
    // construct full file name
    String fileName = imageID + JPEG_SUFFIX;
    File imageFile = new File(context.getExternalFilesDir(Utils.TYPE_PICTURE), fileName);

    // if image file exists trying to load, optimize and decode
    if (imageFile.exists()) {
      // First decode with inJustDecodeBounds=true to check dimensions
      BitmapFactory.Options bmOptions = new BitmapFactory.Options();
      bmOptions.inJustDecodeBounds = true;
      BitmapFactory.decodeFile(imageFile.getAbsolutePath(), bmOptions);
      // Calculate inSampleSize
      bmOptions.inSampleSize = calculateImageInSampleSize(bmOptions, reqSize, reqSize);

      // Decode bitmap with inSampleSize set from file with given options
      bmOptions.inJustDecodeBounds = false;
      bmOptions.inPurgeable = true;
      result = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), bmOptions);
    }
    // if can't be loaded and decoded, load default image from local storage instead
    if (result == null) {
      Log.d(TAG, ".getBitmapFromFilePath(), cann't decode image:" + imageFile.getAbsolutePath());
      File file = new File(context.getExternalFilesDir(TYPE_PICTURE), DEFAULT_IMAGE_NAME);
      result = BitmapFactory.decodeFile(file.getAbsolutePath());
    }
    return result;
  }
예제 #28
0
  /**
   * 通过压缩图片的尺寸来压缩图片大小,通过读入流的方式,可以有效防止网络图片数据流形成位图对象时内存过大的问题;
   *
   * @param InputStream 要压缩图片,以流的形式传入
   * @param targetWidth 缩放的目标宽度
   * @param targetHeight 缩放的目标高度
   * @return 缩放后的图片
   * @throws IOException 读输入流的时候发生异常
   */
  public static Bitmap compressBySize(InputStream is, int targetWidth, int targetHeight)
      throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buff = new byte[1024];
    int len = 0;
    while ((len = is.read(buff)) != -1) {
      baos.write(buff, 0, len);
    }

    byte[] data = baos.toByteArray();
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
    // 得到图片的宽度、高度;
    int imgWidth = opts.outWidth;
    int imgHeight = opts.outHeight;
    // 分别计算图片宽度、高度与目标宽度、高度的比例;取大于该比例的最小整数;
    int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
    int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
    if (widthRatio > 1 && widthRatio > 1) {
      if (widthRatio > heightRatio) {
        opts.inSampleSize = widthRatio;
      } else {
        opts.inSampleSize = heightRatio;
      }
    }
    // 设置好缩放比例后,加载图片进内存;
    opts.inJustDecodeBounds = false;
    bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
    return bitmap;
  }
  private Bitmap comp(Bitmap image) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    if (baos.toByteArray().length / 1024 > 1024) {
      // 判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
      baos.reset(); // 重置baos即清空baos
      image.compress(Bitmap.CompressFormat.JPEG, 50, baos);
      // 这里压缩50%,把压缩后的数据存放到baos中
    }
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
    newOpts.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
    newOpts.inJustDecodeBounds = false;
    int w = newOpts.outWidth;
    int h = newOpts.outHeight;
    // 现在主流手机比较多是800*500分辨率,所以高和宽我们设置为
    float hh = 800f; // 这里设置高度为800f
    float ww = 500f; // 这里设置宽度为500f
    // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
    int be = 1; // be=1表示不缩放
    if (w > h && w > ww) { // 如果宽度大的话根据宽度固定大小缩放
      be = (int) (newOpts.outWidth / ww);
    } else if (w < h && h > hh) { // 如果高度高的话根据宽度固定大小缩放
      be = (int) (newOpts.outHeight / hh);
    }
    if (be <= 0) be = 1;
    newOpts.inSampleSize = be; // 设置缩放比例
    // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
    isBm = new ByteArrayInputStream(baos.toByteArray());
    bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
    return compressImage(bitmap); // 压缩好比例大小后再进行质量压缩
  }
예제 #30
0
  public Bitmap loadImage(String path) throws OutOfMemoryError {
    Bitmap bitsat;

    try {
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inPreferredConfig = Bitmap.Config.ARGB_8888;
      options.inJustDecodeBounds = true;
      Bitmap b = BitmapFactory.decodeFile(path, options);

      options.inSampleSize = Futils.calculateInSampleSize(options, px, px);

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

      Bitmap bit;
      if (path.startsWith("smb:/")) bit = BitmapFactory.decodeStream(new SmbFileInputStream(path));
      else bit = BitmapFactory.decodeFile(path, options);

      bitsat =
          bit; // decodeFile(path);//.createScaledBitmap(bits,imageViewReference.get().getHeight(),imageViewReference.get().getWidth(),true);
    } catch (Exception e) {
      Drawable img = ContextCompat.getDrawable(mContext, R.drawable.ic_doc_image);
      Bitmap img1 = ((BitmapDrawable) img).getBitmap();
      bitsat = img1;
    }
    return bitsat;
  }