Java Code Examples for android.graphics.Bitmap.setDensity()

The following are Jave code examples for showing how to use setDensity() of the android.graphics.Bitmap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: GitHub   File: ConvertUtils.java   View Source Code Vote up 6 votes
public static Bitmap toBitmap(byte[] bytes, int width, int height) {
    Bitmap bitmap = null;
    if (bytes.length != 0) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            // 不进行图片抖动处理
            options.inDither = false;
            // 设置让解码器以最佳方式解码
            options.inPreferredConfig = null;
            if (width > 0 && height > 0) {
                options.outWidth = width;
                options.outHeight = height;
            }
            bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
            bitmap.setDensity(96);// 96 dpi
        } catch (Exception e) {
            LogUtils.error(e);
        }
    }
    return bitmap;
}
 
Example 2
Project: GitHub   File: WebpBitmapFactoryImpl.java   View Source Code Vote up 6 votes
private static void setDensityFromOptions(Bitmap outputBitmap, BitmapFactory.Options opts) {
  if (outputBitmap == null || opts == null) {
    return;
  }

  final int density = opts.inDensity;
  if (density != 0) {
    outputBitmap.setDensity(density);
    final int targetDensity = opts.inTargetDensity;
    if (targetDensity == 0 || density == targetDensity || density == opts.inScreenDensity) {
      return;
    }

    if (opts.inScaled) {
      outputBitmap.setDensity(targetDensity);
    }
  } else if (IN_BITMAP_SUPPORTED && opts.inBitmap != null) {
    // bitmap was reused, ensure density is reset
    outputBitmap.setDensity(DisplayMetrics.DENSITY_DEFAULT);
  }
}
 
Example 3
Project: Renrentou   File: ConvertUtils.java   View Source Code Vote up 6 votes
public static Bitmap toBitmap(byte[] bytes, int width, int height) {
    Bitmap bitmap = null;
    if (bytes.length != 0) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            // 不进行图片抖动处理
            options.inDither = false;
            // 设置让解码器以最佳方式解码
            options.inPreferredConfig = null;
            if (width > 0 && height > 0) {
                options.outWidth = width;
                options.outHeight = height;
            }
            bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
            bitmap.setDensity(96);// 96 dpi
        } catch (Exception e) {
           // LogUtils.error(e);
        }
    }
    return bitmap;
}
 
Example 4
Project: CXJPadProject   File: ConvertUtils.java   View Source Code Vote up 6 votes
public static Bitmap toBitmap(byte[] bytes, int width, int height) {
    Bitmap bitmap = null;
    if (bytes.length != 0) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            // 不进行图片抖动处理
            options.inDither = false;
            // 设置让解码器以最佳方式解码
            options.inPreferredConfig = null;
            if (width > 0 && height > 0) {
                options.outWidth = width;
                options.outHeight = height;
            }
            bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
            bitmap.setDensity(96);// 96 dpi
        } catch (Exception e) {
            LogUtils.error(e);
        }
    }
    return bitmap;
}
 
Example 5
Project: MontageCam   File: BitmapUtils.java   View Source Code Vote up 6 votes
public static Bitmap restoreBitmap(Bitmap src, Matrix matrix, int w, int h) {
    Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
    result.setDensity(src.getDensity());
    Canvas canvas = new Canvas(result);
    float[] data = new float[9];
    matrix.getValues(data);// 底部图片变化记录矩阵原始数据
    Matrix3 cal = new Matrix3(data);// 辅助矩阵计算类
    Matrix3 inverseMatrix = cal.inverseMatrix();// 计算逆矩阵
    Matrix m = new Matrix();
    m.setValues(inverseMatrix.getValues());
    float[] f = new float[9];
    m.getValues(f);
    int dx = (int) f[Matrix.MTRANS_X];
    int dy = (int) f[Matrix.MTRANS_Y];
    float scale_x = f[Matrix.MSCALE_X];
    float scale_y = f[Matrix.MSCALE_Y];
    canvas.save();
    canvas.translate(dx, dy);
    canvas.scale(scale_x, scale_y);
    canvas.drawBitmap(src, 0, 0, null);
    canvas.restore();
    return result;
}
 
Example 6
Project: Accessibility   File: BitmapUtils.java   View Source Code Vote up 6 votes
private static Bitmap createBitmap(Bitmap source, int width, int height, Config config) {
    try {
        if (config == null) {
            config = Config.ARGB_4444;//不要改成565,要不然一些png图会丢失透明信息。
        }
        Bitmap target = createBitmap(width, height, config);
        target.setDensity(source.getDensity());
        Canvas canvas = new Canvas(target);
        Paint paint = new Paint();
        paint.setDither(true);
        paint.setAntiAlias(true);
        Rect src = new Rect(0, 0, source.getWidth(), source.getHeight());
        Rect dst = new Rect(0, 0, width, height);
        canvas.drawBitmap(source, src, dst, paint);
        return target;
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        return source;
    }
}
 
Example 7
Project: GitHub   File: PlatformBitmapFactory.java   View Source Code Vote up 5 votes
/**
 * Creates a bitmap with the specified width and height.  Its initial density is
 * determined from the given DisplayMetrics.
 *
 * @param display Display metrics for the display this bitmap will be drawn on
 * @param width The width of the bitmap
 * @param height The height of the bitmap
 * @param config The bitmap config to create
 * @param hasAlpha If the bitmap is ARGB_8888 this flag can be used to mark the bitmap as opaque
 * Doing so will clear the bitmap in black instead of transparent
 * @param callerContext the Tag to track who create the Bitmap
 * @return a reference to the bitmap
 * @throws IllegalArgumentException if the width or height are <= 0
 * @throws TooManyBitmapsException if the pool is full
 * @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated
 */
private CloseableReference<Bitmap> createBitmap(
    DisplayMetrics display,
    int width,
    int height,
    Bitmap.Config config,
    boolean hasAlpha,
    @Nullable Object callerContext) {
  checkWidthHeight(width, height);
  CloseableReference<Bitmap> bitmapRef = createBitmapInternal(width, height, config);

  Bitmap bitmap = bitmapRef.get();
  if (display != null) {
    bitmap.setDensity(display.densityDpi);
  }

  if (Build.VERSION.SDK_INT >= 12) {
    bitmap.setHasAlpha(hasAlpha);
  }

  if (config == Bitmap.Config.ARGB_8888 && !hasAlpha) {
    bitmap.eraseColor(0xff000000);
  }

  addBitmapReference(bitmapRef.get(), callerContext);
  return bitmapRef;
}
 
Example 8
Project: KB2   File: BattleView.java   View Source Code Vote up 5 votes
private Bitmap flipImage(Bitmap src) {
    Matrix m = new Matrix();
    m.preScale(-1, 1);
    Bitmap dst = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), m, false);
    dst.setDensity(DisplayMetrics.DENSITY_DEFAULT);
    return dst;
}
 
Example 9
Project: MontageCam   File: BitmapUtils.java   View Source Code Vote up 5 votes
public static Bitmap xMirrorBitmap(Bitmap src) {
    Matrix m = new Matrix();
    m.preScale(-1, 1);
    Bitmap result = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), m, true);
    result.setDensity(src.getDensity());
    src.recycle();
    return result;
}
 
Example 10
Project: GitHub   File: Downsampler.java   View Source Code Vote up 4 votes
private Bitmap decodeFromWrappedStreams(InputStream is,
    BitmapFactory.Options options, DownsampleStrategy downsampleStrategy,
    DecodeFormat decodeFormat, int requestedWidth, int requestedHeight,
    boolean fixBitmapToRequestedDimensions, DecodeCallbacks callbacks) throws IOException {

  int[] sourceDimensions = getDimensions(is, options, callbacks);
  int sourceWidth = sourceDimensions[0];
  int sourceHeight = sourceDimensions[1];
  String sourceMimeType = options.outMimeType;

  int orientation = ImageHeaderParserUtils.getOrientation(parsers, is, byteArrayPool);
  int degreesToRotate = TransformationUtils.getExifOrientationDegrees(orientation);

  options.inPreferredConfig = getConfig(is, decodeFormat);
  if (options.inPreferredConfig != Bitmap.Config.ARGB_8888) {
    options.inDither = true;
  }

  int targetWidth = requestedWidth == Target.SIZE_ORIGINAL ? sourceWidth : requestedWidth;
  int targetHeight = requestedHeight == Target.SIZE_ORIGINAL ? sourceHeight : requestedHeight;

  calculateScaling(downsampleStrategy, degreesToRotate, sourceWidth, sourceHeight, targetWidth,
      targetHeight, options);

  boolean isKitKatOrGreater = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
  // Prior to KitKat, the inBitmap size must exactly match the size of the bitmap we're decoding.
  if ((options.inSampleSize == 1 || isKitKatOrGreater)
      && shouldUsePool(is)) {
    int expectedWidth;
    int expectedHeight;
    if (fixBitmapToRequestedDimensions && isKitKatOrGreater) {
      expectedWidth = targetWidth;
      expectedHeight = targetHeight;
    } else {
      float densityMultiplier = isScaling(options)
          ? (float) options.inTargetDensity / options.inDensity : 1f;
      int sampleSize = options.inSampleSize;
      int downsampledWidth = (int) Math.ceil(sourceWidth / (float) sampleSize);
      int downsampledHeight = (int) Math.ceil(sourceHeight / (float) sampleSize);
      expectedWidth = Math.round(downsampledWidth * densityMultiplier);
      expectedHeight = Math.round(downsampledHeight * densityMultiplier);

      if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "Calculated target [" + expectedWidth + "x" + expectedHeight + "] for source"
            + " [" + sourceWidth + "x" + sourceHeight + "]"
            + ", sampleSize: " + sampleSize
            + ", targetDensity: " + options.inTargetDensity
            + ", density: " + options.inDensity
            + ", density multiplier: " + densityMultiplier);
      }
    }
    // If this isn't an image, or BitmapFactory was unable to parse the size, width and height
    // will be -1 here.
    if (expectedWidth > 0 && expectedHeight > 0) {
      setInBitmap(options, bitmapPool, expectedWidth, expectedHeight);
    }
  }
  Bitmap downsampled = decodeStream(is, options, callbacks);
  callbacks.onDecodeComplete(bitmapPool, downsampled);

  if (Log.isLoggable(TAG, Log.VERBOSE)) {
    logDecode(sourceWidth, sourceHeight, sourceMimeType, options, downsampled,
        requestedWidth, requestedHeight);
  }

  Bitmap rotated = null;
  if (downsampled != null) {
    // If we scaled, the Bitmap density will be our inTargetDensity. Here we correct it back to
    // the expected density dpi.
    downsampled.setDensity(displayMetrics.densityDpi);

    rotated = TransformationUtils.rotateImageExif(bitmapPool, downsampled, orientation);
    if (!downsampled.equals(rotated)) {
      bitmapPool.put(downsampled);
    }
  }

  return rotated;
}
 
Example 11
Project: letv   File: DrawingCacheHolder.java   View Source Code Vote up 4 votes
@SuppressLint({"NewApi"})
public void splitWith(int dispWidth, int dispHeight, int maximumCacheWidth, int maximumCacheHeight) {
    recycleBitmapArray();
    if (this.width > 0 && this.height > 0 && this.bitmap != null) {
        if (this.width > maximumCacheWidth || this.height > maximumCacheHeight) {
            maximumCacheWidth = Math.min(maximumCacheWidth, dispWidth);
            maximumCacheHeight = Math.min(maximumCacheHeight, dispHeight);
            int xCount = (this.width / maximumCacheWidth) + (this.width % maximumCacheWidth == 0 ? 0 : 1);
            int yCount = (this.height / maximumCacheHeight) + (this.height % maximumCacheHeight == 0 ? 0 : 1);
            int averageWidth = this.width / xCount;
            int averageHeight = this.height / yCount;
            Bitmap[][] bmpArray = (Bitmap[][]) Array.newInstance(Bitmap.class, new int[]{yCount, xCount});
            if (this.canvas == null) {
                this.canvas = new Canvas();
                if (this.mDensity > 0) {
                    this.canvas.setDensity(this.mDensity);
                }
            }
            Rect rectSrc = new Rect();
            Rect rectDst = new Rect();
            for (int yIndex = 0; yIndex < yCount; yIndex++) {
                for (int xIndex = 0; xIndex < xCount; xIndex++) {
                    Bitmap[] bitmapArr = bmpArray[yIndex];
                    Bitmap bmp = NativeBitmapFactory.createBitmap(averageWidth, averageHeight, Config.ARGB_8888);
                    bitmapArr[xIndex] = bmp;
                    if (this.mDensity > 0) {
                        bmp.setDensity(this.mDensity);
                    }
                    this.canvas.setBitmap(bmp);
                    int left = xIndex * averageWidth;
                    int top = yIndex * averageHeight;
                    rectSrc.set(left, top, left + averageWidth, top + averageHeight);
                    rectDst.set(0, 0, bmp.getWidth(), bmp.getHeight());
                    this.canvas.drawBitmap(this.bitmap, rectSrc, rectDst, null);
                }
            }
            this.canvas.setBitmap(this.bitmap);
            this.bitmapArray = bmpArray;
        }
    }
}
 
Example 12
Project: AirQuickUtils   File: AirAnimation.java   View Source Code Vote up 4 votes
public static List<AnimationFrame> createAnimationDrawableList(Context context, File directory, FilenameFilter filter, int width, int height) throws IllegalArgumentException {
    if (directory == null || directory.isDirectory() == false) {
        throw new IllegalArgumentException("Argument isn't directory. "+directory);
    }

    File[] files = null;

    if (filter == null) {
        files = directory.listFiles();
    } else {
        files = directory.listFiles(filter);
    }

    if (files.length == 0) {
        throw new IllegalArgumentException("The directory is empty. " + directory);
    }

    Arrays.sort(files, new Comparator<File>() {
        @Override
        public int compare(File lhs, File rhs) {
            return lhs.compareTo(rhs);
        }
    });

    List<AnimationFrame> drawables = new ArrayList<AnimationFrame>(files.length);

    for (File file : files) {
        AnimationFrame frame = new AnimationFrame();

        // Extract duration from file name.
        frame.setDuration(getDurationFromFileName(file.getName()));

        // Create BitmapDrawlable.
        Bitmap bitmap = null;

        try {
            bitmap = AirQuickUtils.image.resizeImage(context, file, width, height);
        }
        catch(IOException e) {
            AirQuickUtils.log.e("Can't resize bimtap.");
            continue;
        }

        bitmap.setDensity(DisplayMetrics.DENSITY_MEDIUM);

        BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
        bitmapDrawable.setAntiAlias(true);

        frame.setDrawable(bitmapDrawable);

        drawables.add(frame);
        AirQuickUtils.log.e(" Frame >> Path: " + file.getAbsoluteFile() + ", Duration: " + frame.getDuration());
    }

    return drawables;
}