예제 #1
0
 /**
  * Create a new instance of Icon representing a custom icon.
  *
  * @param ctx Context.
  * @param rawIconUri URI of the image to use as icon.
  * @return New instance of {@link CustomIcon}, or {@code null} if an error occurred.
  */
 public static Icon newIcon(Context ctx, Uri rawIconUri) {
   return CustomIcon.createIcon(ctx, rawIconUri);
 }
예제 #2
0
    /**
     * Create an instance of {@link CustomIcon} given the URI of an image.
     *
     * @param ctx Context.
     * @param rawIconUri URI of the image to use as icon.
     * @return New instance of {@link CustomIcon}, or {@code null} if an error occurred.
     */
    protected static CustomIcon createIcon(Context ctx, Uri rawIconUri) {
      CustomIcon retVal = null;

      // Import image locally
      File tmpIconFile = CustomIcon.getTempFile(ctx);
      InputStream fis;
      OutputStream fos;
      int byteCount;
      byte[] buffer = new byte[2048];
      boolean imported = false;

      try {
        fis = ctx.getContentResolver().openInputStream(rawIconUri);
        try {
          fos = new FileOutputStream(tmpIconFile);
          try {
            while ((byteCount = fis.read(buffer)) > 0) {
              fos.write(buffer, 0, byteCount);
            }
            imported = true;
          } finally {
            fos.close();
          }
        } finally {
          fis.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }

      if (!imported) {
        return null;
      }

      // Load scaled image
      Bitmap image = Helper.getIconFromImage(tmpIconFile.getAbsolutePath(), ICON_SIZE, ICON_SIZE);

      if (image == null) {
        return null;
      }

      // Save resized image and compute Md5
      MessageDigest md5;
      String hash = null;

      try {
        // Compress & save icon
        fos = new FileOutputStream(tmpIconFile);
        try {
          image.compress(Bitmap.CompressFormat.PNG, 100, fos);
        } finally {
          fos.close();
        }

        // Compute md5
        md5 = MessageDigest.getInstance("MD5");

        fis = new FileInputStream(tmpIconFile);
        try {
          while ((byteCount = fis.read(buffer)) > 0) {
            md5.update(buffer, 0, byteCount);
          }
          hash = Helper.bytesToHex(md5.digest());
        } finally {
          fis.close();
        }
      } catch (Exception e) {
        // Something went wrong.
        hash = null;
        e.printStackTrace();
      }

      if (hash != null) {
        retVal = new CustomIcon(hash, tmpIconFile.getAbsolutePath());
        Log.i(
            TAG,
            "createIcon: Imported from " + rawIconUri.toString() + " to " + retVal.getIconPath());
      } else {
        Log.w(TAG, "createIcon: Cannot import from " + rawIconUri.toString());
      }

      return retVal;
    }