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); // 压缩好比例大小后再进行质量压缩
  }
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
      if (requestCode == REQUEST_CAMERA) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        imageBytes = bytes.toByteArray();
        File destination =
            new File(
                Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
        FileOutputStream fo;
        try {
          destination.createNewFile();
          fo = new FileOutputStream(destination);
          fo.write(bytes.toByteArray());
          fo.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        image.setImageBitmap(thumbnail);
      } else if (requestCode == SELECT_FILE) {
        Bitmap bitmap = data.getExtras().getParcelable("data");
        image.setImageBitmap(bitmap);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        // Compress image to lower quality scale 1 - 100
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        imageBytes = stream.toByteArray();
      }
      uploadButton.setEnabled(true);
    }
  }
Ejemplo n.º 3
0
 /**
  * 将bitmap保存到本地
  *
  * @param mBitmap
  * @param imagePath
  */
 @SuppressLint("NewApi")
 public static void saveBitmap(Bitmap bitmap, String imagePath, int s) {
   File file = new File(imagePath);
   createDipPath(imagePath);
   FileOutputStream fOut = null;
   try {
     fOut = new FileOutputStream(file);
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   }
   if (imagePath.toLowerCase().endsWith(".png")) {
     bitmap.compress(Bitmap.CompressFormat.PNG, s, fOut);
   } else if (imagePath.toLowerCase().endsWith(".jpg")) {
     bitmap.compress(Bitmap.CompressFormat.JPEG, s, fOut);
   } else {
     bitmap.compress(Bitmap.CompressFormat.WEBP, s, fOut);
   }
   try {
     fOut.flush();
   } catch (IOException e) {
     e.printStackTrace();
   }
   try {
     fOut.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 4
0
  public void selectProfilePicture(Intent data) {

    Uri selectedImage = data.getData();

    try {

      Bitmap finalImage = ImageHandler.getPortraitImage(selectedImage, getActivity(), 300, 200);
      profilePicture.setImageBitmap(finalImage);

      Bitmap thumbNail = ImageHandler.getPortraitImage(selectedImage, getActivity(), 35, 23);

      // http://stackoverflow.com/questions/26292969/can-i-store-image-files-in-firebase-using-java-api
      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      finalImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
      String imageString = Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT);

      stream.reset();
      thumbNail.compress(Bitmap.CompressFormat.PNG, 100, stream);
      String thumbNString = Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT);

      MainActivity.getUser().setProfilePicture(imageString, stream.toByteArray());
      stream.close();

      new FbDataChange("/users/" + MainActivity.getUser().getUid() + "/profilePicture", imageString)
          .execute();

      new FbDataChange("/users/" + MainActivity.getUser().getUid() + "/profileThumb", thumbNString)
          .execute();
    } catch (IOException e) {
    }
  }
Ejemplo n.º 5
0
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {

          Bitmap BMP_MEAL_IMAGE;

          if (imgSource == 1) {
            BMP_MEAL_IMAGE = resizeCameraBitmap(bitmap);

            imgvwAddPhoto.setImageBitmap(BMP_MEAL_IMAGE);
            imgvwAddPhoto.setScaleType(AppCompatImageView.ScaleType.CENTER_CROP);

            /** CONVERT THE BITMAP TO A BYTE ARRAY * */
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            BMP_MEAL_IMAGE.compress(Bitmap.CompressFormat.PNG, 100, bos);
            MEAL_IMAGE = bos.toByteArray();

          } else if (imgSource == 2) {
            imgvwAddPhoto.setImageBitmap(bitmap);
            imgvwAddPhoto.setScaleType(AppCompatImageView.ScaleType.CENTER_CROP);

            /** CONVERT THE BITMAP TO A BYTE ARRAY * */
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
            MEAL_IMAGE = bos.toByteArray();
          }
        }
Ejemplo n.º 6
0
 /**
  * 将位图保存到指定路径
  *
  * @param bm
  * @param path
  */
 public static String save(Bitmap bm, String path) {
   File file = null;
   if (bm != null && path != null) {
     file = new File(path);
     // 如果父目录不存在,创建父目录
     if (!file.getParentFile().exists()) {
       file.getParentFile().mkdirs();
     }
     try {
       if (!file.exists()) {
         try {
           file.createNewFile();
         } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
         }
       }
       FileOutputStream out = new FileOutputStream(file);
       // 获取拓展名
       String filename = file.getName();
       String ext = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
       if ("jpg".equalsIgnoreCase(ext) || "jpeg".equalsIgnoreCase(ext)) {
         bm.compress(CompressFormat.JPEG, 100, out);
       } else {
         bm.compress(CompressFormat.PNG, 100, out);
       }
     } catch (FileNotFoundException e) {
       e.printStackTrace();
     }
   }
   return file.getAbsolutePath();
 }
Ejemplo n.º 7
0
  private void saveScreenshot(Bitmap bitmap, String format, String fileName, Integer quality) {
    try {
      File folder = new File(Environment.getExternalStorageDirectory(), "Pictures");
      if (!folder.exists()) {
        folder.mkdirs();
      }

      File f = new File(folder, fileName + "." + format);

      FileOutputStream fos = new FileOutputStream(f);
      if (format.equals("png")) {
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
      } else if (format.equals("jpg")) {
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality == null ? 100 : quality, fos);
      }
      JSONObject jsonRes = new JSONObject();
      jsonRes.put("filePath", f.getAbsolutePath());
      PluginResult result = new PluginResult(PluginResult.Status.OK, jsonRes);
      mCallbackContext.sendPluginResult(result);

      scanPhoto(f.getAbsolutePath());
      fos.close();
    } catch (JSONException e) {
      mCallbackContext.error(e.getMessage());

    } catch (IOException e) {
      mCallbackContext.error(e.getMessage());
    }
  }
Ejemplo n.º 8
0
 public static File saveBitmap(Bitmap bmp, String id, Context context) {
   File file = getFile(id, context);
   if (!file.exists() && !file.isDirectory()) {
     try {
       FileOutputStream out = new FileOutputStream(file);
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       int quality = 100;
       bmp.compress(Bitmap.CompressFormat.PNG, quality, baos);
       Log.d("图片压缩前大小:" + baos.toByteArray().length / 1024 + "kb");
       if (baos.toByteArray().length / 1024 > 50) {
         quality = 80;
         baos.reset();
         bmp.compress(Bitmap.CompressFormat.PNG, quality, baos);
         Log.d("质量压缩到原来的" + quality + "%时大小为:" + baos.toByteArray().length / 1024 + "kb");
       }
       Log.d("图片压缩后大小:" + baos.toByteArray().length / 1024 + "kb");
       baos.writeTo(out);
       baos.flush();
       baos.close();
       out.close();
       //				bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return file;
 }
Ejemplo n.º 9
0
  /**
   * 压缩图片大小
   *
   * @param bitmap 图片
   * @param maxSize 压缩最大大小
   * @return
   */
  public static Bitmap compressImage(Bitmap bitmap, double maxSize) {
    // 图片允许最大空间   单位:KB
    //        double maxSize = 100.00;
    int option = 100;
    // 将bitmap放至数组中,意在bitmap的大小(与实际读取的原文件要大)
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, option, baos);
    byte[] b = baos.toByteArray();

    // 将字节换成KB
    double mid = b.length / 1024;
    // 判断bitmap占用空间是否大于允许最大空间  如果大于则压缩 小于则不压缩
    while (mid > maxSize) {
      baos.reset();
      option -= 10;
      bitmap.compress(Bitmap.CompressFormat.JPEG, option, baos);
      mid = baos.toByteArray().length / 1024;
      if (option == 30) {
        break;
      }
    }
    ByteArrayInputStream isBm =
        new ByteArrayInputStream(baos.toByteArray()); // 把压缩后的数据baos存放到ByteArrayInputStream中
    bitmap = BitmapFactory.decodeStream(isBm, null, null); // 把ByteArrayInputStream数据生成图片
    if (mid > maxSize) {
      double i = mid / maxSize;
      return zoomImage(bitmap, bitmap.getWidth() / Math.sqrt(i), bitmap.getHeight() / Math.sqrt(i));
    }
    return bitmap;
  }
Ejemplo n.º 10
0
 /**
  * 尺寸和大小都压缩 ,压缩到一兆 尺寸压缩有待验证
  *
  * @param src
  * @param height
  * @param width
  * @return
  */
 public static Bitmap compressImage(Bitmap src, int height, int width) {
   if (src == null) {
     return null;
   }
   Bitmap scaledBitmap = Bitmap.createScaledBitmap(src, width, height, false);
   int compress = 90;
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   scaledBitmap.compress(
       Bitmap.CompressFormat.JPEG, compress, baos); // 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
   while (baos.toByteArray().length > 100 * 1024) {
     baos.reset(); // 重置baos即清空baos
     scaledBitmap.compress(
         Bitmap.CompressFormat.JPEG, compress, baos); // 这里压缩options%,把压缩后的数据存放到baos中
     compress -= 10; // 每次都减少10
     if (compress <= 0) {
       break;
     }
   }
   ByteArrayInputStream isBm =
       new ByteArrayInputStream(baos.toByteArray()); // 把压缩后的数据baos存放到ByteArrayInputStream中
   Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null); // 把ByteArrayInputStream数据生成图片
   try {
     baos.close();
     isBm.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return bitmap;
 }
Ejemplo n.º 11
0
  private String encodeAndScaleImage(String imagePath) {

    Bitmap original = BitmapFactory.decodeFile(imagePath);
    if (original == null) return null;

    // the smallest size has to be constant
    // the other size should scale accordingly
    int width = original.getWidth();
    int height = original.getHeight();
    if (width <= height) {
      float ratio = (float) height / (float) width;
      width = Consts.THUMB_MIN_SIZE;
      height = (int) (width * ratio);
    } else {
      float ratio = (float) height / (float) width;
      height = Consts.THUMB_MIN_SIZE;
      width = (int) (height * ratio);
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // if image is larger than 1024px X 1024px (by longest side)
    if (!(original.getWidth() < Consts.THUMB_MIN_SIZE
        || original.getHeight() < Consts.THUMB_MIN_SIZE)) {
      // resize picture to 1024px X 1024px (by longest side)
      Bitmap scaledBitmap = Bitmap.createScaledBitmap(original, width, height, true);
      scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);
    } else original.compress(Bitmap.CompressFormat.JPEG, 90, baos);

    byte[] byteArrayImage = baos.toByteArray();
    return Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
  }
Ejemplo n.º 12
0
 // 同比缩放解决方案---图片按比例大小压缩方法(根据Bitmap图片压缩)
 public static Bitmap compressByBitmap(
     Bitmap srcBitmap, int dstWidth, int dstHeight, int sizeInKb, ScalingLogic scalingLogic) {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
   int quality = 100;
   while (baos.toByteArray().length / 1024
       > 1024) { // 判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
     baos.reset(); // 重置baos即清空baos
     srcBitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos); // 这里压缩quality%,把压缩后的数据存放到baos中
     quality -= 10; // 每次都减少10
   }
   ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
   BitmapFactory.Options options = new BitmapFactory.Options();
   // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
   options.inJustDecodeBounds = true;
   Bitmap bitmap = BitmapFactory.decodeStream(bais, null, options);
   int inSampleSize =
       calculateSampleSize(options.outWidth, options.outHeight, dstWidth, dstHeight, scalingLogic);
   options.inSampleSize = inSampleSize > 0 ? inSampleSize : 1; // 设置缩放比例
   options.inJustDecodeBounds = false;
   options.inPreferredConfig = Bitmap.Config.RGB_565;
   options.inPurgeable = true;
   options.inInputShareable = true;
   // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
   bais = new ByteArrayInputStream(baos.toByteArray());
   bitmap = BitmapFactory.decodeStream(bais, null, options);
   return compressImage(bitmap, sizeInKb); // 压缩好比例大小后再进行质量压缩
 }
Ejemplo n.º 13
0
  /** 压缩图片, 成为Base64 String */
  public static String compressPic(Bitmap oriBitmap) {
    int wid = oriBitmap.getWidth(), hgt = oriBitmap.getHeight();
    // System.out.println("w="+wid+",h="+hgt);
    Bitmap rb = null;
    if (wid > 800 || hgt > 800) {
      float max = 800;
      float scale;
      if (wid > hgt) {
        scale = max / wid;
      } else {
        scale = max / hgt;
      }
      Matrix matrix = new Matrix();
      matrix.postScale(scale, scale); // 参数为比率

      rb = Bitmap.createBitmap(oriBitmap, 0, 0, wid, hgt, matrix, true);
    } else rb = oriBitmap;

    ByteArrayOutputStream bStream = new ByteArrayOutputStream();

    int prs = 100;
    rb.compress(CompressFormat.JPEG, 100, bStream);

    while (bStream.toByteArray().length > 1024 * 100 && prs > 0) { // 大于100k
      prs -= 10;
      bStream.reset();
      rb.compress(CompressFormat.JPEG, prs, bStream);
    }
    // System.out.println(bStream.toByteArray().length);
    String s = Base64.encodeToString(bStream.toByteArray(), Base64.DEFAULT);

    return s;
  }
Ejemplo n.º 14
0
  private String saveBitmap(
      Context context, Bitmap bmp, int type, String dir, String fileName, Boolean isCover) {
    if (bmp == null) {
      return null;
    }

    String picPath = null;

    picPath = dir + "/" + fileName;

    // 判断文件夹是否存在
    File picFile = new File(dir);
    if (!picFile.exists()) {
      picFile.mkdir();
    }

    File file = new File(picPath);
    if (file.exists()) {
      if (isCover) {
        file.delete();
      } else {
        return picPath;
      }
    }

    try {
      file.createNewFile();
    } catch (IOException e1) {
      return null;
    }

    FileOutputStream fOut = null;
    try {
      fOut = new FileOutputStream(file);
      switch (type) {
        case JPG:
          bmp.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
          break;
        default:
          bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
          break;
      }

    } catch (FileNotFoundException e) {
      Log.e(TAG, e.getMessage());
    }

    try {
      fOut.flush();
    } catch (IOException e) {
      Log.e(TAG, e.getMessage());
    }
    try {
      fOut.close();
    } catch (IOException e) {
      Log.e(TAG, e.getMessage());
    }

    return picPath;
  }
Ejemplo n.º 15
0
    /**
     * Saves a file.
     *
     * @param name the name of the file
     * @param b the bitmap to save
     * @param quality the compression rate. From 0 (compress for lowest size) to 100 (compress for
     *     maximum quality).
     */
    private void saveFile(String name, Bitmap b, int quality) {
      FileOutputStream fos = null;
      String fileName = getFileName(name);

      File directory = new File(config.screenshotSavePath);
      directory.mkdir();

      File fileToSave = new File(directory, fileName);
      try {
        fos = new FileOutputStream(fileToSave);
        if (config.screenshotFileType == ScreenshotFileType.JPEG) {
          if (b.compress(Bitmap.CompressFormat.JPEG, quality, fos) == false) {
            Log.d(LOG_TAG, "Compress/Write failed");
          }
        } else {
          if (b.compress(Bitmap.CompressFormat.PNG, quality, fos) == false) {
            Log.d(LOG_TAG, "Compress/Write failed");
          }
        }
        fos.flush();
        fos.close();
      } catch (Exception e) {
        Log.d(
            LOG_TAG,
            "Can't save the screenshot! Requires write permission (android.permission.WRITE_EXTERNAL_STORAGE) in AndroidManifest.xml of the application under test.");
        e.printStackTrace();
      }
    }
Ejemplo n.º 16
0
    private static void revitionImageSize(String picfile, int size, int quality)
        throws IOException {
      if (size <= 0) {
        throw new IllegalArgumentException("size must be greater than 0!");
      }

      if (!doesExisted(picfile)) {
        throw new FileNotFoundException(picfile == null ? "null" : picfile);
      }

      if (!BitmapHelper.verifyBitmap(picfile)) {
        throw new IOException("");
      }

      FileInputStream input = new FileInputStream(picfile);
      final BitmapFactory.Options opts = new BitmapFactory.Options();
      opts.inJustDecodeBounds = true;
      BitmapFactory.decodeStream(input, null, opts);
      try {
        input.close();
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      int rate = 0;
      for (int i = 0; ; i++) {
        if ((opts.outWidth >> i <= size) && (opts.outHeight >> i <= size)) {
          rate = i;
          break;
        }
      }

      opts.inSampleSize = (int) Math.pow(2, rate);
      opts.inJustDecodeBounds = false;

      Bitmap temp = safeDecodeBimtapFile(picfile, opts);

      if (temp == null) {
        throw new IOException("Bitmap decode error!");
      }

      deleteDependon(picfile);
      makesureFileExist(picfile);
      final FileOutputStream output = new FileOutputStream(picfile);
      if (opts != null && opts.outMimeType != null && opts.outMimeType.contains("png")) {
        temp.compress(Bitmap.CompressFormat.PNG, quality, output);
      } else {
        temp.compress(Bitmap.CompressFormat.JPEG, quality, output);
      }
      try {
        output.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
      temp.recycle();
    }
Ejemplo n.º 17
0
 public static byte[] bitmapToByteArray(Bitmap bitmap, int compressQuality) {
   ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
   if (bitmap.hasAlpha()) {
     bitmap.compress(Bitmap.CompressFormat.PNG, compressQuality, localByteArrayOutputStream);
   } else {
     bitmap.compress(Bitmap.CompressFormat.JPEG, compressQuality, localByteArrayOutputStream);
   }
   byte[] result = localByteArrayOutputStream.toByteArray();
   IOUtils.closeQuietly(localByteArrayOutputStream);
   return result;
 }
Ejemplo n.º 18
0
  // 根据路径获得图片并压缩
  public static String getSmallImgePath(Context context, String filePath) {

    if (filePath == null || filePath.length() == 0) {
      return "";
    }
    String endStr = filePath.substring(filePath.lastIndexOf("."), filePath.length());

    File file = null;

    try {

      int degree = readPictureDegree(filePath);

      BitmapFactory.Options options = new BitmapFactory.Options();

      options.inJustDecodeBounds = true;
      BitmapFactory.decodeFile(filePath, options);
      int inSampleSize = calculateInSampleSize(options, 480, 800);
      if (inSampleSize >= 4) {
        inSampleSize++;
      }
      options.inSampleSize = inSampleSize;
      options.inJustDecodeBounds = false;
      Bitmap bm = BitmapFactory.decodeFile(filePath, options);

      if (degree != 0) {
        bm = rotaingImage(degree, bm);
      }

      if (bm != null) {
        int width = Math.min(bm.getWidth(), bm.getHeight());
        bm = centerSquareScaleBitmap(bm, width);
        file = new File(context.getCacheDir() + "/temp" + System.currentTimeMillis() + endStr);
        FileOutputStream fileOutputStream = new FileOutputStream(file);

        if (endStr.equalsIgnoreCase(".png")) {
          bm.compress(Bitmap.CompressFormat.PNG, 80, fileOutputStream);
        } else {
          bm.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream);
        }

        fileOutputStream.close();
        bm.recycle();
      }

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

    if (file != null) {
      return file.getAbsolutePath();
    }
    return null;
  }
  /**
   * 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;
  }
Ejemplo n.º 20
0
 // 图片质量压缩方法
 private static Bitmap compressImage(Bitmap image) {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   image.compress(Bitmap.CompressFormat.JPEG, 100, baos); // 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
   int options = 100;
   while (baos.toByteArray().length / 1024 > 50) { // 循环判断如果压缩后图片是否大于50kb,大于继续压缩
     baos.reset(); // 重置baos即清空baos
     options -= 10; // 每次都减少10
     image.compress(Bitmap.CompressFormat.JPEG, options, baos); // 这里压缩options%,把压缩后的数据存放到baos中
   }
   ByteArrayInputStream isBm =
       new ByteArrayInputStream(baos.toByteArray()); // 把压缩后的数据baos存放到ByteArrayInputStream中
   Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null); // 把ByteArrayInputStream数据生成图片
   return bitmap;
 }
Ejemplo n.º 21
0
 /**
  * 图片质量压缩
  *
  * @param srcBitmap
  * @param sizeInKb
  * @return
  */
 public static Bitmap compressImage(Bitmap srcBitmap, int sizeInKb) {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); // 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
   int options = 100;
   while (baos.toByteArray().length / 1024 > sizeInKb) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
     baos.reset(); // 重置baos即清空baos
     srcBitmap.compress(Bitmap.CompressFormat.JPEG, options, baos); // 这里压缩options%,把压缩后的数据存放到baos中
     options -= 10; // 每次都减少10
   }
   ByteArrayInputStream bais =
       new ByteArrayInputStream(baos.toByteArray()); // 把压缩后的数据baos存放到ByteArrayInputStream中
   Bitmap bitmap = BitmapFactory.decodeStream(bais, null, null); // 把ByteArrayInputStream数据生成图片
   return bitmap;
 }
Ejemplo n.º 22
0
  public void testValues() {
    CompressFormat[] comFormat = CompressFormat.values();

    assertEquals(3, comFormat.length);
    assertEquals(CompressFormat.JPEG, comFormat[0]);
    assertEquals(CompressFormat.PNG, comFormat[1]);
    assertEquals(CompressFormat.WEBP, comFormat[2]);

    // CompressFormat is used as a argument here for all the methods that use it
    Bitmap b = Bitmap.createBitmap(10, 24, Config.ARGB_8888);
    assertTrue(b.compress(CompressFormat.JPEG, 24, new ByteArrayOutputStream()));
    assertTrue(b.compress(CompressFormat.PNG, 24, new ByteArrayOutputStream()));
    assertTrue(b.compress(CompressFormat.WEBP, 24, new ByteArrayOutputStream()));
  }
Ejemplo n.º 23
0
 /**
  * 通过降低图片的质量来压缩图片
  *
  * @param bmp 要压缩的图片
  * @param maxSize 压缩后图片大小的最大值,单位KB
  * @return 压缩后的图片
  */
 public static Bitmap compressByQuality(Bitmap bitmap, int maxSize) {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   int quality = 100;
   bitmap.compress(CompressFormat.JPEG, quality, baos);
   System.out.println("图片压缩前大小:" + baos.toByteArray().length + "byte");
   while (baos.toByteArray().length / 1024 > maxSize) {
     quality -= 10;
     baos.reset();
     bitmap.compress(CompressFormat.JPEG, quality, baos);
     System.out.println("质量压缩到原来的" + quality + "%时大小为:" + baos.toByteArray().length + "byte");
   }
   System.out.println("图片压缩后大小:" + baos.toByteArray().length + "byte");
   bitmap = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length);
   return bitmap;
 }
Ejemplo n.º 24
0
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   if (resultCode == RESULT_OK) {
     if (requestCode == 0) {
       Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
       ByteArrayOutputStream bytes = new ByteArrayOutputStream();
       thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
       File destination =
           new File(
               Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
       FileOutputStream fo;
       try {
         destination.createNewFile();
         fo = new FileOutputStream(destination);
         fo.write(bytes.toByteArray());
         fo.close();
       } catch (FileNotFoundException e) {
         e.printStackTrace();
       } catch (IOException e) {
         e.printStackTrace();
       }
       btnImage.setImageBitmap(thumbnail);
     } else if (requestCode == 1) {
       Uri selectedImageUri = data.getData();
       String[] projection = {MediaStore.MediaColumns.DATA};
       Cursor cursor = managedQuery(selectedImageUri, projection, null, null, null);
       int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
       cursor.moveToFirst();
       String selectedImagePath = cursor.getString(column_index);
       Bitmap bm;
       BitmapFactory.Options options = new BitmapFactory.Options();
       options.inJustDecodeBounds = true;
       BitmapFactory.decodeFile(selectedImagePath, options);
       final int REQUIRED_SIZE = 200;
       int scale = 1;
       while (options.outWidth / scale / 2 >= REQUIRED_SIZE
           && options.outHeight / scale / 2 >= REQUIRED_SIZE) scale *= 2;
       options.inSampleSize = scale;
       options.inJustDecodeBounds = false;
       bm = BitmapFactory.decodeFile(selectedImagePath, options);
       btnImage.setImageBitmap(bm);
       ByteArrayOutputStream stream = new ByteArrayOutputStream();
       bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
       image = stream.toByteArray();
     }
   }
 }
Ejemplo n.º 25
0
 // convert bitmap to base64
 public static String bitmapToBase64(Bitmap bitmap) {
   String result = null;
   ByteArrayOutputStream baos = null;
   try {
     if (bitmap != null) {
       baos = new ByteArrayOutputStream();
       bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
       baos.flush();
       baos.close();
       byte[] bitmapBytes = baos.toByteArray();
       result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
     }
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       if (baos != null) {
         baos.flush();
         baos.close();
       }
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   return result;
 }
  private void saveBmpToSd(Bitmap bm, String url) {
    if (bm == null) {
      Log.w(TAG, " trying to savenull bitmap");
      return;
    }
    // 判断sdcard上的空间
    //        if (FREE_SD_SPACE_NEEDED_TO_CACHE >freeSpaceOnSd()) {
    //            Log.w(TAG, "Low free space onsd, do not cache");
    //            return;
    //        }

    File file = new File(Environment.getExternalStorageDirectory() + "/cache/" + MD5(url) + ".jpg");
    try {
      file.createNewFile();
      OutputStream outStream = new FileOutputStream(file);
      bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
      outStream.flush();
      outStream.close();
      Log.i(TAG, "Image saved tosd");
    } catch (FileNotFoundException e) {
      Log.w(TAG, "FileNotFoundException");
    } catch (IOException e) {
      Log.w(TAG, "IOException");
    }
  }
 private byte[] convertImage(int resImage) {
   Bitmap bitmap = BitmapFactory.decodeResource(getActivity().getResources(), resImage);
   ByteArrayOutputStream stream = new ByteArrayOutputStream();
   bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
   // bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
   return stream.toByteArray();
 }
  @Override
  public void shortcutPicked(String uri, String friendlyName, Bitmap bmp, boolean isApplication) {
    NavBarButton button = mButtons.get(mPendingButton);
    boolean longpress = button.getPickLongPress();

    if (!longpress) {
      button.setClickAction(uri);
      if (bmp == null) {
        button.setIconURI("");
      } else {
        String iconName = getIconFileName(mPendingButton);
        FileOutputStream iconStream = null;
        try {
          iconStream = mContext.openFileOutput(iconName, Context.MODE_WORLD_READABLE);
        } catch (FileNotFoundException e) {
          return; // NOOOOO
        }
        bmp.compress(Bitmap.CompressFormat.PNG, 100, iconStream);
        button.setIconURI(Uri.fromFile(mContext.getFileStreamPath(iconName)).toString());
      }
    } else {
      button.setLongPress(uri);
    }
    refreshButtons();
  }
Ejemplo n.º 29
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 saveMyBitmap() {
		try {
		Bitmap bitmap = mGesture.toBitmap(240, 75, 12, Color.RED);
		// mImageView.setImageBitmap(bitmap);
		if(path == null || path.equals("") || path.equals("null")){
		path = Environment.getExternalStorageDirectory().toString();
		}
		Log.e("?????", path);
		
		  File destDir = new File(path);
		  if (!destDir.exists()) {
		   destDir.mkdirs();
		  }
		
		String name = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date())
				+ ".png";// 照片命名
		
		this.pathAndName = path + "/"+name;
		File f = new File(pathAndName);
		
		
		FileOutputStream fos = null;
		
			fos = new FileOutputStream(f);
			bitmap.compress(Bitmap.CompressFormat.PNG, 50, fos);
			Toast.makeText(getApplicationContext(), "保存成功", 5000).show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.e("Exception", e.getMessage());
			e.printStackTrace();
		}
	}