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

The following examples show how to use android.graphics.Bitmap#setDensity() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConvertUtils.java    From AndroidPicker with MIT License 8 votes vote down vote up
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
Source File: ConvertUtils.java    From a with GNU General Public License v3.0 6 votes vote down vote up
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) {
        }
    }
    return bitmap;
}
 
Example 3
Source File: ConvertUtils.java    From FilePicker with MIT License 6 votes vote down vote up
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
Source File: ConvertUtils.java    From MyBookshelf with GNU General Public License v3.0 6 votes vote down vote up
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) {
        }
    }
    return bitmap;
}
 
Example 5
Source File: ConvertUtils.java    From AndroidDownload with Apache License 2.0 6 votes vote down vote up
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 6
Source File: BlurTransform.java    From Amphitheatre with Apache License 2.0 6 votes vote down vote up
@Override
public Bitmap transform(Bitmap in) {
    Bitmap out = Bitmap.createBitmap(in.getWidth(), in.getHeight(), in.getConfig());
    out.setDensity(in.getDensity());

    RenderScript rs = RenderScript.create(context);
    Allocation input = Allocation.createFromBitmap(rs, in);
    Allocation output = Allocation.createFromBitmap(rs, out);

    ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, getElement(in, rs));
    script.setInput(input);
    script.setRadius(20);
    script.forEach(output);

    output.copyTo(out);
    in.recycle();

    rs.destroy();

    return out;
}
 
Example 7
Source File: WebpBitmapFactoryImpl.java    From fresco with MIT License 6 votes vote down vote up
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 8
Source File: PlatformBitmapFactory.java    From fresco with MIT License 6 votes vote down vote up
/**
 * 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);
  }

  return bitmapRef;
}
 
Example 9
Source File: FillWidthImageView.java    From AndroidCommons with Apache License 2.0 5 votes vote down vote up
@Override
public void setImageBitmap(Bitmap bm) {
    if (bm == null) {
        setImageDrawable(null);
    } else {
        BitmapDrawable drawable = new BitmapDrawable(getResources(), bm);
        bm.setDensity(Bitmap.DENSITY_NONE);
        setImageDrawable(drawable);
    }
}
 
Example 10
Source File: Util.java    From FlappyCow with MIT License 5 votes vote down vote up
public static Bitmap getDownScaledBitmapAlpha8(Context context, int id) {
    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inPreferredConfig = Bitmap.Config.ALPHA_8;
    bitmapOptions.inScaled = true;
    bitmapOptions.inDensity = DEFAULT_DENSITY;
    bitmapOptions.inTargetDensity = Math.min((int)(getScaleFactor(context)*DEFAULT_DENSITY), DEFAULT_DENSITY);
    Bitmap b = BitmapFactory.decodeResource(context.getResources(), id, bitmapOptions);
    b.setDensity(context.getResources().getDisplayMetrics().densityDpi);
    return b;
}
 
Example 11
Source File: Util.java    From FlappyCow with MIT License 5 votes vote down vote up
public static Bitmap getScaledBitmapAlpha8(Context context, int id) {
    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inPreferredConfig = Bitmap.Config.ALPHA_8;
    bitmapOptions.inScaled = true;
    bitmapOptions.inDensity = DEFAULT_DENSITY;
    bitmapOptions.inTargetDensity = (int)(getScaleFactor(context)*DEFAULT_DENSITY);
    Bitmap b = BitmapFactory.decodeResource(context.getResources(), id, bitmapOptions);
    b.setDensity(context.getResources().getDisplayMetrics().densityDpi);
    return b;
}
 
Example 12
Source File: PlatformBitmapFactory.java    From fresco with MIT License 5 votes vote down vote up
/**
 * Set some property of the source bitmap to the destination bitmap
 *
 * @param source the source bitmap
 * @param destination the destination bitmap
 */
private static void setPropertyFromSourceBitmap(Bitmap source, Bitmap destination) {
  // The new bitmap was created from a known bitmap source so assume that
  // they use the same density
  destination.setDensity(source.getDensity());
  if (Build.VERSION.SDK_INT >= 12) {
    destination.setHasAlpha(source.hasAlpha());
  }

  if (Build.VERSION.SDK_INT >= 19) {
    destination.setPremultiplied(source.isPremultiplied());
  }
}
 
Example 13
Source File: OC_PlayZoneVideo.java    From GLEXP-Team-onebillion with Apache License 2.0 5 votes vote down vote up
public void finishRecording() throws Exception
{
    if (recording)
    {
        recording = false;
        videoRecorder.stopRecording();
        cameraManager.stopPreview();
        playSFX("click");

        try
        {
            Bitmap bitmap = getFirstFrameForVideo(videoFilePath);
            Matrix m = new Matrix();
            float thumbScale = 0.3f;
            m.preScale((videoOrientationFront ? -1 : 1) * thumbScale, thumbScale);
            Bitmap dst = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, false);

            dst.setDensity(DisplayMetrics.DENSITY_DEFAULT);
            FileOutputStream out = new FileOutputStream(thumbnailFilePath);
            dst.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.close();

            OCM_FatController fatController = (OCM_FatController)MainActivity.mainActivity.fatController;
            Map<String,String> map = new ArrayMap<>();
            map.put("video", videoFileName);
            map.put("mirrored",String.valueOf(videoOrientationFront));
            fatController.savePlayZoneAssetForCurrentUserType(OC_PlayZoneAsset.ASSET_VIDEO,thumbnalFileName,map);
            OBUtils.runOnOtherThread(new OBUtils.RunLambda()
            {
                public void run() throws Exception
                {
                    animateRecordFinish();
                }
            });
        }catch (Exception e)
        {
            exitEvent();
        }
    }
}
 
Example 14
Source File: RepeaterIconSettingDialog.java    From QNotified with GNU General Public License v3.0 5 votes vote down vote up
public static Bitmap getRepeaterIcon() {
    if (sCachedRepeaterIcon != null) {
        return sCachedRepeaterIcon;
    }
    ConfigManager cfg = ConfigManager.getDefaultConfig();
    byte[] data = (byte[]) cfg.getAllConfig().get(qn_repeat_icon_data);
    int dpi = cfg.getIntOrDefault(qn_repeat_icon_dpi, 0);
    if (data != null) {
        Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
        if (bm != null) {
            if (dpi > 0) {
                bm.setDensity(dpi);
            }
            sCachedRepeaterIcon = bm;
        }
    }
    if (sCachedRepeaterIcon == null) {
        InputStream in = ResUtils.openAsset("repeat.png");
        if (in != null) {
            sCachedRepeaterIcon = BitmapFactory.decodeStream(in);
            try {
                in.close();
            } catch (IOException ignored) {
            }
            sCachedRepeaterIcon.setDensity(320);
        } else {
            Utils.loge("getRepeaterIcon/E ResUtils.openAsset(\"repeat.png\") == null");
        }
    }
    return sCachedRepeaterIcon;
}
 
Example 15
Source File: BitmapTransformation.java    From glide-transformations with Apache License 2.0 4 votes vote down vote up
void setCanvasBitmapDensity(@NonNull Bitmap toTransform, @NonNull Bitmap canvasBitmap) {
  canvasBitmap.setDensity(toTransform.getDensity());
}
 
Example 16
Source File: TopAnchorFillWidthTransformation.java    From edx-app-android with Apache License 2.0 4 votes vote down vote up
@Override
protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform,
                           int outWidth, int outHeight) {
    final int width = toTransform.getWidth();
    final float widthRatio = outWidth / (float) width;

    /*
     Implementation Details:
     Following if-condition is an optimization to just match the aspect ratio of the View where
     the Bitmap has a smaller width, and not artificially scale up the Bitmap (as ImageView
     will automatically scale it up to match it's coordinates unless explicitly set not to do
     so). However, Glide uses a TransitionDrawable to transition from the placeholder to the
     actual image, and as we can't guarantee that the placeholder would also have a matching
     aspect ratio, this can cause the scaling to not be performed properly to fill the View.

     If we're always using a scaleType of fitXY or centerCrop in all our ImageView items, then
     we should not encounter any issues. However, if we might use fitCenter (the default),
     center, or centerInside scale types. we'll need to do following 2 things:
     1) Remove width and height manipulation (Done by removing the following if-section).
     2) Make the canvas scaling unconditional (Done by taking the line canvas.scale(....) out
     of the if-block).

     Since, we're using fitXY as our scaleType wherever we are applying this transformation, so
     the following condition gives us memory benefits.
     */
    if (outWidth > width) {
        outWidth = width;
        outHeight = Math.round(outHeight / widthRatio);
    }
    Bitmap newBitmap = Bitmap.createBitmap(
            outWidth, outHeight, toTransform.getConfig());
    newBitmap.setDensity(toTransform.getDensity());
    newBitmap.setPremultiplied(true);
    Canvas canvas = new Canvas(newBitmap);
    // It looks like Canvas has black color by default, and
    // there doesn't seem to be any simple way to set it as
    // transparent.
    canvas.drawColor(Color.WHITE);
    if (outWidth < width) {
        canvas.scale(widthRatio, widthRatio);
    }
    canvas.drawBitmap(toTransform, 0, 0, paint);
    return newBitmap;
}
 
Example 17
Source File: DrawingCacheHolder.java    From letv with Apache License 2.0 4 votes vote down vote up
@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 18
Source File: EncodeDecode.java    From Image-Steganography-Library-Android with MIT License 4 votes vote down vote up
/**
 * This method implements the above method on the list of chunk image list.
 *
 * @return : Encoded list of chunk images
 * @parameter : splitted_images {list of chunk images}
 * @parameter : encrypted_message {string}
 * @parameter : progressHandler {Progress bar handler}
 */
public static List<Bitmap> encodeMessage(List<Bitmap> splitted_images,
                                         String encrypted_message, ProgressHandler progressHandler) {

    //Making result method

    List<Bitmap> result = new ArrayList<>(splitted_images.size());


    //Adding start and end message constants to the encrypted message
    encrypted_message = encrypted_message + END_MESSAGE_COSTANT;
    encrypted_message = START_MESSAGE_COSTANT + encrypted_message;


    //getting byte array from string
    byte[] byte_encrypted_message = encrypted_message.getBytes(Charset.forName("ISO-8859-1"));

    //Message Encoding Status
    MessageEncodingStatus message = new MessageEncodingStatus(byte_encrypted_message, encrypted_message);

    //Progress Handler
    if (progressHandler != null) {
        progressHandler.setTotal(encrypted_message.getBytes(Charset.forName("ISO-8859-1")).length);
    }

    //Just a log to get the byte message length
    Log.i(TAG, "Message length " + byte_encrypted_message.length);

    for (Bitmap bitmap : splitted_images) {

        if (!message.isMessageEncoded()) {

            //getting bitmap height and width
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();

            //Making 1D integer pixel array
            int[] oneD = new int[width * height];
            bitmap.getPixels(oneD, 0, width, 0, 0, width, height);

            //getting bitmap density
            int density = bitmap.getDensity();

            //encoding image
            byte[] encodedImage = encodeMessage(oneD, width, height, message, progressHandler);

            //converting byte_image_array to integer_array
            int[] oneDMod = Utility.byteArrayToIntArray(encodedImage);

            //creating bitmap from encrypted_image_array
            Bitmap encoded_Bitmap = Bitmap.createBitmap(width, height,
                    Bitmap.Config.ARGB_8888);
            encoded_Bitmap.setDensity(density);

            int masterIndex = 0;

            //setting pixel values of above bitmap
            for (int j = 0; j < height; j++)
                for (int i = 0; i < width; i++) {

                    encoded_Bitmap.setPixel(i, j, Color.argb(0xFF,
                            oneDMod[masterIndex] >> 16 & 0xFF,
                            oneDMod[masterIndex] >> 8 & 0xFF,
                            oneDMod[masterIndex++] & 0xFF));

                }

            result.add(encoded_Bitmap);

        } else {
            //Just add the image chunk to the result
            result.add(bitmap.copy(bitmap.getConfig(), false));
        }
    }

    return result;
}