Java Code Examples for android.graphics.Bitmap

The following are top voted examples for showing how to use android.graphics.Bitmap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: exciting-app   File: FileUtil.java   Source Code and License 7 votes vote down vote up
/**
 * 获取图片文件的宽高,宽高封装在Point的X和Y中
 *
 * @param filePath 文件路径
 */
public static Point getPicWH(String filePath) {
    Point point = new Point();
    try {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
        point.x = options.outWidth;
        point.y = options.outHeight;
        options.inJustDecodeBounds = false;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return point;
}
 
Example 2
Project: AliZhiBoHao   File: PushParamsActivity.java   Source Code and License 7 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case GET_PHOTO:
            if (resultCode == RESULT_OK) {
                crop(data.getData());
            }
            break;
        case TAKE_PHOTO:
            if (resultCode == RESULT_OK) {
                crop(headImgUri);
            }
            break;
        case CROP_PHOTO:
            if (resultCode == RESULT_OK) {
                Bitmap cropBitmap = data.getParcelableExtra("data");
                String path = mUriFile.getPath();
                watermarkUrl = path;
                pickDirectory.setImageBitmap(cropBitmap);
                mCustomPopupWindow.dismiss();
            }
            break;
        default:
            break;
    }
}
 
Example 3
Project: pc-android-controller-android   File: ImageCompressUtil.java   Source Code and License 6 votes vote down vote up
/**
         * @param b Bitmap
         * @return 图片存储的位置
         */
        public static File saveImg(Bitmap b, String name) throws Exception {
            String path = Environment.getExternalStorageDirectory().getPath() + File.separator + "test/headImg/";
            File mediaFile = new File(path + File.separator + name + ".jpg");
            if (mediaFile.exists()) {
                mediaFile.delete();

            }
            if (!new File(path).exists()) {
                new File(path).mkdirs();
            }
            mediaFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(mediaFile);
            b.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
            b.recycle();
            b = null;
            System.gc();
//            return mediaFile.getPath();
            return mediaFile;
        }
 
Example 4
Project: Watermark   File: MarkPresenter.java   Source Code and License 6 votes vote down vote up
public Bitmap getBitmapByView(View v) {
    Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
            Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    v.draw(canvas);
    return bitmap;
}
 
Example 5
Project: fast_face_android   File: FaceDetTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDetFace() {
    Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/test.jpg");
    assertThat(bitmap, notNullValue());
    FaceDet faceDet = new FaceDet(Constants.getFaceShapeModelPath());
    List<VisionDetRet> results = faceDet.detect("/sdcard/test.jpg");
    for (final VisionDetRet ret : results) {
        String label = ret.getLabel();
        int rectLeft = ret.getLeft();
        int rectTop = ret.getTop();
        int rectRight = ret.getRight();
        int rectBottom = ret.getBottom();
        assertThat(label, is("face"));
        Assert.assertTrue(rectLeft > 0);
    }
    faceDet.release();
}
 
Example 6
Project: PicShow-zhaipin   File: XCRoundImageView.java   Source Code and License 6 votes vote down vote up
/**
 * 获取圆形图片方法
 * @param bitmap
 * @param pixels
 * @return Bitmap
 * @author caizhiming
 */
private Bitmap getCircleBitmap(Bitmap bitmap, int pixels) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
            bitmap.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final int color = 0xff424242;

    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    int x = bitmap.getWidth();

    canvas.drawCircle(x / 2, x / 2, x / 2, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);
    return output;


}
 
Example 7
Project: GitHub   File: GingerbreadPurgeableDecoder.java   Source Code and License 6 votes vote down vote up
protected Bitmap decodeFileDescriptorAsPurgeable(
    CloseableReference<PooledByteBuffer> bytesRef,
    int inputLength,
    byte[] suffix,
    BitmapFactory.Options options) {
  MemoryFile memoryFile = null;
  try {
    memoryFile = copyToMemoryFile(bytesRef, inputLength, suffix);
    FileDescriptor fd = getMemoryFileDescriptor(memoryFile);
    Bitmap bitmap = sWebpBitmapFactory.decodeFileDescriptor(fd, null, options);
    return Preconditions.checkNotNull(bitmap, "BitmapFactory returned null");
  } catch (IOException e) {
    throw Throwables.propagate(e);
  } finally {
    if (memoryFile != null) {
      memoryFile.close();
    }
  }
}
 
Example 8
Project: RunHDU   File: ImageUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 对Activity截图
 *
 * @param activity
 * @return Bitmap对象。
 */
public static Bitmap takeScreenShot(Activity activity) {
    View view = activity.getWindow().getDecorView();
    view.setDrawingCacheEnabled(true);
    view.buildDrawingCache();
    Bitmap b1 = view.getDrawingCache();
    Rect frame = new Rect();
    activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
    int statusBarHeight = frame.top;
    int width = activity.getWindowManager().getDefaultDisplay().getWidth();
    int height = activity.getWindowManager().getDefaultDisplay()
            .getHeight();
    Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
    view.destroyDrawingCache();
    return b;
}
 
Example 9
Project: localcloud_fe   File: CameraLauncher.java   Source Code and License 6 votes vote down vote up
/**
 * Compress bitmap using jpeg, convert to Base64 encoded string, and return to JavaScript.
 *
 * @param bitmap
 */
public void processPicture(Bitmap bitmap) {
    ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream();
    try {
        if (bitmap.compress(CompressFormat.JPEG, mQuality, jpeg_data)) {
            byte[] code = jpeg_data.toByteArray();
            byte[] output = Base64.encode(code, Base64.NO_WRAP);
            String js_out = new String(output);
            this.callbackContext.success(js_out);
            js_out = null;
            output = null;
            code = null;
        }
    } catch (Exception e) {
        this.failPicture("Error compressing image.");
    }
    jpeg_data = null;
}
 
Example 10
Project: mvparms   File: FastBlur.java   Source Code and License 6 votes vote down vote up
public static void blur(Bitmap bkg, View view) {
    long startMs = System.currentTimeMillis();
    float radius = 15;
    float scaleFactor = 8;
    //放大到整个view的大小
    bkg = DrawableProvider.getReSizeBitmap(bkg, view.getMeasuredWidth(), view.getMeasuredHeight());

    Bitmap overlay = Bitmap.createBitmap((int) (view.getMeasuredWidth() / scaleFactor)
            , (int) (view.getMeasuredHeight() / scaleFactor), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(overlay);
    canvas.translate(-view.getLeft() / scaleFactor, -view.getTop() / scaleFactor);
    canvas.scale(1 / scaleFactor, 1 / scaleFactor);
    Paint paint = new Paint();
    paint.setFlags(Paint.FILTER_BITMAP_FLAG);
    canvas.drawBitmap(bkg, 0, 0, paint);
    overlay = FastBlur.doBlur(overlay, (int) radius, true);
    view.setBackgroundDrawable(new BitmapDrawable(UiUtils.getResources(), overlay));
    Log.w("test", "cost " + (System.currentTimeMillis() - startMs) + "ms");
}
 
Example 11
Project: TripBuyer   File: AuthenticationActivity.java   Source Code and License 6 votes vote down vote up
/**
 * 上传用户信息,首先上传头像,上传成功后赶回头像地址,然后上传其他信息
 */


private void updateUserInfo(Bitmap avatar) {

    //如果头像为空,也就是用户没有上传头像,则使用之前的头像地址
    if (avatar == null) {

    } else {
        final AVFile avatarFile = new AVFile("user_avatar.jpeg", ImageUtil.bitmap2Bytes(avatar));
        avatarFile.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {

                    Log.i("lin", "----lin---->  imgUrl" + avatarFile.getUrl());
                    _cardView = avatarFile.getUrl();

                }
            }
        });
    }
}
 
Example 12
Project: androidgithub   File: FriendListItem.java   Source Code and License 6 votes vote down vote up
public void update(Following following, boolean fling) {
	tvName.setText(following.screenName);
	ivCheck.setImageBitmap(following.checked ? bmChd : bmUnch);
	if (aivIcon != null) {
		if (fling) {
			Bitmap bm = BitmapProcessor.getBitmapFromCache(following.icon);
			if (bm != null && !bm.isRecycled()) {
				aivIcon.setImageBitmap(bm);
			} else {
				aivIcon.execute(null, 0);
			}
		} else {
			aivIcon.execute(following.icon, 0);
		}
	}
}
 
Example 13
Project: decoy   File: BitmapDecoder.java   Source Code and License 6 votes vote down vote up
public static Bitmap decodeSampled(InputStream is, int reqWidth, int reqHeight) {
    BitmapFactory.Options options = new BitmapFactory.Options();

    // RGB_565
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    // sample size
    options.inSampleSize = getSampleSize(is, reqWidth, reqHeight);

    try {
        return BitmapFactory.decodeStream(is, null, options);
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 14
Project: musicwidget   File: NotificationListenerKK.java   Source Code and License 6 votes vote down vote up
@Override
public void onClientMetadataUpdate(RemoteController.MetadataEditor metadataEditor) {
    meta=metadataEditor;
    StandardWidget.currentArt=metadataEditor.getBitmap(MediaMetadataEditor.BITMAP_KEY_ARTWORK,null);
    StandardWidget.currentSquareArt = StandardWidget.currentArt;
    if(StandardWidget.currentArt!=null) {
        int cah = StandardWidget.currentArt.getHeight();
        int caw = StandardWidget.currentArt.getWidth();
        if (caw > cah * 1.02) {
            StandardWidget.currentSquareArt = Bitmap.createBitmap(StandardWidget.currentArt,
                    (int) (caw / 2 - cah * 0.51), 0, (int) (cah * 1.02), cah);
        }
    }
    StandardWidget.currentArtist=metadataEditor.getString(MediaMetadataRetriever.METADATA_KEY_ARTIST,"");
    StandardWidget.currentSong=metadataEditor.getString(MediaMetadataRetriever.METADATA_KEY_TITLE,"");
    StandardWidget.currentAlbum=metadataEditor.getString(MediaMetadataRetriever.METADATA_KEY_ALBUM,"");
    if(StandardWidget.currentArtist==null||StandardWidget.currentArtist.equals("")){
        StandardWidget.currentArtist = metadataEditor.getString(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST,"");
    }
    if(StandardWidget.currentArtist==null||StandardWidget.currentArtist.equals("")){
        StandardWidget.currentArtist = metadataEditor.getString(MediaMetadataRetriever.METADATA_KEY_AUTHOR,"");
    }
    sendBroadcast(new Intent(StandardWidget.WIDGET_UPDATE));
}
 
Example 15
Project: FlickLauncher   File: IconCache.java   Source Code and License 6 votes vote down vote up
/**
 * Generates a new low-res icon given a high-res icon.
 */
private Bitmap generateLowResIcon(Bitmap icon, int lowResBackgroundColor) {
    if (lowResBackgroundColor == Color.TRANSPARENT) {
        return Bitmap.createScaledBitmap(icon,
                        icon.getWidth() / LOW_RES_SCALE_FACTOR,
                        icon.getHeight() / LOW_RES_SCALE_FACTOR, true);
    } else {
        Bitmap lowResIcon = Bitmap.createBitmap(icon.getWidth() / LOW_RES_SCALE_FACTOR,
                icon.getHeight() / LOW_RES_SCALE_FACTOR, Bitmap.Config.RGB_565);
        synchronized (this) {
            mLowResCanvas.setBitmap(lowResIcon);
            mLowResCanvas.drawColor(lowResBackgroundColor);
            mLowResCanvas.drawBitmap(icon, new Rect(0, 0, icon.getWidth(), icon.getHeight()),
                    new Rect(0, 0, lowResIcon.getWidth(), lowResIcon.getHeight()),
                    mLowResPaint);
            mLowResCanvas.setBitmap(null);
        }
        return lowResIcon;
    }
}
 
Example 16
Project: google-maps-clustering   File: DefaultIconGenerator.java   Source Code and License 6 votes vote down vote up
@NonNull
private BitmapDescriptor createClusterIcon(int clusterBucket) {
    @SuppressLint("InflateParams")
    TextView clusterIconView = (TextView) LayoutInflater.from(mContext)
            .inflate(R.layout.map_cluster_icon, null);
    clusterIconView.setBackground(createClusterBackground());
    clusterIconView.setTextColor(mIconStyle.getClusterTextColor());
    clusterIconView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
            mIconStyle.getClusterTextSize());

    clusterIconView.setText(getClusterIconText(clusterBucket));

    clusterIconView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
    clusterIconView.layout(0, 0, clusterIconView.getMeasuredWidth(),
            clusterIconView.getMeasuredHeight());

    Bitmap iconBitmap = Bitmap.createBitmap(clusterIconView.getMeasuredWidth(),
            clusterIconView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(iconBitmap);
    clusterIconView.draw(canvas);

    return BitmapDescriptorFactory.fromBitmap(iconBitmap);
}
 
Example 17
Project: event-me   File: CircleTransform.java   Source Code and License 6 votes vote down vote up
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
    if (toTransform == null) return null;

    int size = Math.min(toTransform.getWidth(), toTransform.getHeight());
    int x = (toTransform.getWidth() - size) / 2;
    int y = (toTransform.getHeight() - size) / 2;

    Bitmap squared = Bitmap.createBitmap(toTransform, x, y, size, size);

    Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
    if (result == null) {
        result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
    }

    Canvas canvas = new Canvas(result);
    Paint paint = new Paint();
    paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
    paint.setAntiAlias(true);
    float r = size / 2f;
    canvas.drawCircle(r, r, r, paint);
    return result;
}
 
Example 18
Project: GitHub   File: BitmapAnimationBackendTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDrawNewBitmap() {
  when(mPlatformBitmapFactory.createBitmap(anyInt(), anyInt(), any(Bitmap.Config.class)))
      .thenReturn(mBitmapRefererence);
  when(mBitmapFrameRenderer.renderFrame(anyInt(), any(Bitmap.class))).thenReturn(true);

  mBitmapAnimationBackend.drawFrame(mParentDrawable, mCanvas, 2);

  verify(mFrameListener).onDrawFrameStart(mBitmapAnimationBackend, 2);
  verify(mBitmapFrameCache).getCachedFrame(2);
  verify(mBitmapFrameCache).getBitmapToReuseForFrame(2, 0, 0);
  verify(mPlatformBitmapFactory).createBitmap(0, 0, Bitmap.Config.ARGB_8888);
  verify(mBitmapFrameRenderer).renderFrame(2, mBitmap);
  verify(mCanvas).drawBitmap(eq(mBitmap), eq(0f), eq(0f), any(Paint.class));
  verifyFramePreparationStrategyCalled(2);
  verifyListenersAndCacheNotified(2, BitmapAnimationBackend.FRAME_TYPE_CREATED);
  assertReferencesClosed();
}
 
Example 19
Project: chat-sdk-android-push-firebase   File: MakeThreadImage.java   Source Code and License 6 votes vote down vote up
@Override
protected void onPostExecute(Bitmap bitmap) {
    super.onPostExecute(bitmap);

    if (bitmap != null)
    {
        // Save image to cache.
        VolleyUtils.getBitmapCache().put(getCacheKey(cacheKey, urlsLength), bitmap);
    }

    if (!isCancelled())
    {
        if (bitmap != null) {
            {
                image.setImageBitmap(bitmap);

                if (progressBar!=null)
                {
                    progressBar.setVisibility(View.INVISIBLE);
                    image.setVisibility(View.VISIBLE);
                }
            }
        } else setMultipleUserDefaultImg();
    }
}
 
Example 20
Project: JkImageLoader   File: JkImageLoader.java   Source Code and License 6 votes vote down vote up
/**
 * Constructor
 * @author leibing
 * @createTime 2017/3/2
 * @lastModify 2017/3/2
 * @param context ref
 * @return
 */
private JkImageLoader(Context context){
    // init application conext
    mApplicationContext = context.getApplicationContext();
    // init memory cache(one 8 of the max memory)
    int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    int cacheSize = maxMemory / 8;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
        }
    };
    // init disk cache
    initDiskCache();
}
 
Example 21
Project: Ocr-android   File: BitmapUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 旋转bitmap
 *
 * @param origin bitmap
 * @param alpha  旋转角度
 * @return 旋转后的bitmap
 */
public static Bitmap rotateBitmap(Bitmap origin, float alpha) {
    if (origin == null || origin.isRecycled()) {
        return null;
    }
    int width = origin.getWidth();
    int height = origin.getHeight();
    Matrix matrix = new Matrix();
    matrix.setRotate(alpha);
    Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
    if (newBM.equals(origin)) {
        return newBM;
    }
    origin.recycle();
    return newBM;
}
 
Example 22
Project: GitHub   File: AttributeStrategyTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testLeastRecentlyUsedAttributeSetIsRemovedFirst() {
  final Bitmap leastRecentlyUsed = ShadowBitmap.createBitmap(100, 100, Bitmap.Config.ALPHA_8);
  final Bitmap other = ShadowBitmap.createBitmap(1000, 1000, Bitmap.Config.RGB_565);
  final Bitmap mostRecentlyUsed = ShadowBitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);

  strategy.get(100, 100, Bitmap.Config.ALPHA_8);
  strategy.get(1000, 1000, Bitmap.Config.RGB_565);
  strategy.get(100, 100, Bitmap.Config.ARGB_8888);

  strategy.put(other);
  strategy.put(leastRecentlyUsed);
  strategy.put(mostRecentlyUsed);

  Bitmap removed = strategy.removeLast();
  assertEquals(
      "Expected=" + strategy.logBitmap(leastRecentlyUsed) + " got=" + strategy.logBitmap(removed),
      leastRecentlyUsed, removed);
}
 
Example 23
Project: Mobike   File: QrUtils.java   Source Code and License 6 votes vote down vote up
/**
 * YUV420sp
 *
 * @param inputWidth
 * @param inputHeight
 * @param scaled
 * @return
 */
public static byte[] getYUV420sp(int inputWidth, int inputHeight, Bitmap scaled) {
    int[] argb = new int[inputWidth * inputHeight];

    scaled.getPixels(argb, 0, inputWidth, 0, 0, inputWidth, inputHeight);

    /**
     * 需要转换成偶数的像素点,否则编码YUV420的时候有可能导致分配的空间大小不够而溢出。
     */
    int requiredWidth = inputWidth % 2 == 0 ? inputWidth : inputWidth + 1;
    int requiredHeight = inputHeight % 2 == 0 ? inputHeight : inputHeight + 1;

    int byteLength = requiredWidth * requiredHeight * 3 / 2;
    if (yuvs == null || yuvs.length < byteLength) {
        yuvs = new byte[byteLength];
    } else {
        Arrays.fill(yuvs, (byte) 0);
    }

    encodeYUV420SP(yuvs, argb, inputWidth, inputHeight);

    scaled.recycle();

    return yuvs;
}
 
Example 24
Project: Taxi-App-Android-XML   File: Home.java   Source Code and License 6 votes vote down vote up
public Bitmap getBitmapFromView(String title, int dotBg) {

        LinearLayout llmarker = (LinearLayout) findViewById(R.id.ll_marker);
        TextView markerImageView = (TextView) findViewById(R.id.tv_title);
        markerImageView.setText(title);
        View dot = (View) findViewById(R.id.dot_marker);
        dot.setBackgroundResource(dotBg);

        llmarker.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        Bitmap bitmap = Bitmap.createBitmap(llmarker.getMeasuredWidth(), llmarker.getMeasuredHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        llmarker.layout(0, 0, llmarker.getMeasuredWidth(), llmarker.getMeasuredHeight());
        llmarker.draw(canvas);
        return bitmap;
    }
 
Example 25
Project: decoy   File: ImageLoaderKit.java   Source Code and License 6 votes vote down vote up
/**
 * 获取通知栏提醒所需的头像位图,只存内存缓存/磁盘缓存中取,如果没有则返回空,自动发起异步加载
 * 注意:该方法在后台线程执行
 */
public Bitmap getNotificationBitmapFromCache(String url) {
    if (TextUtils.isEmpty(url)) {
        return null;
    }
    final int imageSize = HeadImageView.DEFAULT_AVATAR_NOTIFICATION_ICON_SIZE;

    Bitmap cachedBitmap = null;
    try {
        cachedBitmap = Glide.with(context)
                .load(url)
                .asBitmap()
                .centerCrop()
                .into(imageSize, imageSize)
                .get(200, TimeUnit.MILLISECONDS); // 最大等待200ms
    } catch (Exception e) {
        e.printStackTrace();
    }

    return cachedBitmap;
}
 
Example 26
Project: airgram   File: SecretPhotoViewer.java   Source Code and License 6 votes vote down vote up
public void closePhoto() {
    NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messagesDeleted);
    NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didCreatedNewDeleteTask);
    if (parentActivity == null) {
        return;
    }
    currentMessageObject = null;
    isVisible = false;
    AndroidUtilities.unlockOrientation(parentActivity);
    AndroidUtilities.runOnUIThread(new Runnable() {
        @Override
        public void run() {
            centerImage.setImageBitmap((Bitmap)null);
        }
    });
    try {
        if (windowView.getParent() != null) {
            WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE);
            wm.removeView(windowView);
        }
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}
 
Example 27
Project: chromium-for-android-56-debug-video   File: RoundedIconGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * Generates an icon based on |text|.
 *
 * @param text The text to render the first character of on the icon.
 * @return The generated icon.
 */
public Bitmap generateIconForText(String text) {
    Bitmap icon = Bitmap.createBitmap(mIconWidthPx, mIconHeightPx, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(icon);

    canvas.drawRoundRect(mBackgroundRect, mCornerRadiusPx, mCornerRadiusPx, mBackgroundPaint);

    String displayText = text.substring(0, 1).toUpperCase(Locale.getDefault());
    float textWidth = mTextPaint.measureText(displayText);

    canvas.drawText(
            displayText,
            (mIconWidthPx - textWidth) / 2f,
            Math.round((Math.max(mIconHeightPx, mTextHeight) - mTextHeight)
                    / 2.0f + mTextYOffset),
            mTextPaint);

    return icon;
}
 
Example 28
Project: GitHub   File: Util.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the in memory size of the given {@link Bitmap} in bytes.
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
public static int getBitmapByteSize(Bitmap bitmap) {
  // The return value of getAllocationByteCount silently changes for recycled bitmaps from the
  // internal buffer size to row bytes * height. To avoid random inconsistencies in caches, we
  // instead assert here.
  if (bitmap.isRecycled()) {
    throw new IllegalStateException("Cannot obtain size for recycled Bitmap: " + bitmap
        + "[" + bitmap.getWidth() + "x" + bitmap.getHeight() + "] " + bitmap.getConfig());
  }
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    // Workaround for KitKat initial release NPE in Bitmap, fixed in MR1. See issue #148.
    try {
      return bitmap.getAllocationByteCount();
    } catch (NullPointerException e) {
      // Do nothing.
    }
  }
  return bitmap.getHeight() * bitmap.getRowBytes();
}
 
Example 29
Project: airgram   File: PhotoPickerActivity.java   Source Code and License 5 votes vote down vote up
@Override
public Bitmap getThumbForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) {
    PhotoPickerPhotoCell cell = getCellForIndex(index);
    if (cell != null) {
        return cell.photoImage.getImageReceiver().getBitmap();
    }
    return null;
}
 
Example 30
Project: letv   File: AuthAgent.java   Source Code and License 5 votes vote down vote up
private Drawable a(String str, Context context) {
    Drawable createFromStream;
    IOException e;
    try {
        InputStream open = context.getApplicationContext().getAssets().open(str);
        if (open == null) {
            return null;
        }
        if (str.endsWith(".9.png")) {
            Bitmap decodeStream = BitmapFactory.decodeStream(open);
            if (decodeStream == null) {
                return null;
            }
            byte[] ninePatchChunk = decodeStream.getNinePatchChunk();
            NinePatch.isNinePatchChunk(ninePatchChunk);
            return new NinePatchDrawable(decodeStream, ninePatchChunk, new Rect(), null);
        }
        createFromStream = Drawable.createFromStream(open, str);
        try {
            open.close();
            return createFromStream;
        } catch (IOException e2) {
            e = e2;
            e.printStackTrace();
            return createFromStream;
        }
    } catch (IOException e3) {
        IOException iOException = e3;
        createFromStream = null;
        e = iOException;
        e.printStackTrace();
        return createFromStream;
    }
}
 
Example 31
Project: GitHub   File: ImageLoader.java   Source Code and License 5 votes vote down vote up
/**
 * Constructs a BitmapContainer object.
 * @param bitmap The final bitmap (if it exists).
 * @param requestUrl The requested URL for this container.
 * @param cacheKey The cache key that identifies the requested URL for this container.
 */
public ImageContainer(Bitmap bitmap, String requestUrl,
        String cacheKey, ImageListener listener) {
    mBitmap = bitmap;
    mRequestUrl = requestUrl;
    mCacheKey = cacheKey;
    mListener = listener;
}
 
Example 32
Project: youth-health   File: MemoryCache.java   Source Code and License 5 votes vote down vote up
public Bitmap get(String id){
    try{
        if(!cache.containsKey(id))
            return null;
        return cache.get(id);
    }catch(NullPointerException ex){
        ex.printStackTrace();
        return null;
    }
}
 
Example 33
Project: RLibrary   File: ACache.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("deprecation")
private static Drawable bitmap2Drawable(Bitmap bm) {
    if (bm == null) {
        return null;
    }
    return new BitmapDrawable(bm);
}
 
Example 34
Project: BlueTape   File: BlueTapeDslTest.java   Source Code and License 5 votes vote down vote up
@Test
public void imageBitmap() throws Exception {
    // Given
    ImageView imageView = mock(ImageView.class);
    Bitmap bitmap = mock(Bitmap.class);

    // When
    BlueTapeDsl
            .imageBitmap(bitmap)
            .bind(imageView);

    // Then
    verify(imageView).setImageBitmap(bitmap);
}
 
Example 35
Project: Depth   File: NoiseEffect.java   Source Code and License 5 votes vote down vote up
public NoiseEffect(Bitmap bitmap, int grainFPS, float scale) {
    super(bitmap, 0, 0);
    shader = new BitmapShader(bitmap, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
    matrix = new Matrix();

    shader.setLocalMatrix(matrix);
    paint.setShader(shader);
    paint.setAlpha(144);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SCREEN));
    lastGrainOffset = System.currentTimeMillis();
    this.grainFPS = grainFPS;
    this.scale=scale;
}
 
Example 36
Project: FlickLauncher   File: WidgetPreviewLoader.java   Source Code and License 5 votes vote down vote up
private Bitmap generatePreview(Launcher launcher, WidgetItem item, Bitmap recycle,
        int previewWidth, int previewHeight) {
    if (item.widgetInfo != null) {
        return generateWidgetPreview(launcher, item.widgetInfo,
                previewWidth, recycle, null);
    } else {
        return generateShortcutPreview(launcher, item.activityInfo,
                previewWidth, previewHeight, recycle);
    }
}
 
Example 37
Project: GitHub   File: BaseImageDecoder.java   Source Code and License 5 votes vote down vote up
/**
 * Decodes image from URI into {@link Bitmap}. Image is scaled close to incoming {@linkplain ImageSize target size}
 * during decoding (depend on incoming parameters).
 *
 * @param decodingInfo Needed data for decoding image
 * @return Decoded bitmap
 * @throws IOException                   if some I/O exception occurs during image reading
 * @throws UnsupportedOperationException if image URI has unsupported scheme(protocol)
 */
@Override
public Bitmap decode(ImageDecodingInfo decodingInfo) throws IOException {
	Bitmap decodedBitmap;
	ImageFileInfo imageInfo;

	InputStream imageStream = getImageStream(decodingInfo);
	if (imageStream == null) {
		L.e(ERROR_NO_IMAGE_STREAM, decodingInfo.getImageKey());
		return null;
	}
	try {
		imageInfo = defineImageSizeAndRotation(imageStream, decodingInfo);
		imageStream = resetStream(imageStream, decodingInfo);
		Options decodingOptions = prepareDecodingOptions(imageInfo.imageSize, decodingInfo);
		decodedBitmap = BitmapFactory.decodeStream(imageStream, null, decodingOptions);
	} finally {
		IoUtils.closeSilently(imageStream);
	}

	if (decodedBitmap == null) {
		L.e(ERROR_CANT_DECODE_IMAGE, decodingInfo.getImageKey());
	} else {
		decodedBitmap = considerExactScaleAndOrientatiton(decodedBitmap, decodingInfo, imageInfo.exif.rotation,
				imageInfo.exif.flipHorizontal);
	}
	return decodedBitmap;
}
 
Example 38
Project: GitHub   File: ImageUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 获取bitmap
 *
 * @param resId 资源id
 * @return bitmap
 */
public static Bitmap getBitmap(@DrawableRes final int resId) {
    Drawable drawable = ContextCompat.getDrawable(Utils.getApp(), resId);
    Canvas canvas = new Canvas();
    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    canvas.setBitmap(bitmap);
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
    drawable.draw(canvas);
    return bitmap;
}
 
Example 39
Project: empty-state-recyclerview   File: ImageStateDisplay.java   Source Code and License 5 votes vote down vote up
public void resizeImage(int width, int height) {
    if (image == null) {
        throw new NullPointerException("Please set an image before calling resizeImage()!");
    }
    this.image = Bitmap.createScaledBitmap(image, width, height, false);
    invalidateImage();
}
 
Example 40
Project: GitHub   File: BitmapHunterTest.java   Source Code and License 5 votes vote down vote up
@Test public void huntDecodesWhenNotInCache() throws Exception {
  Action action = mockAction(URI_KEY_1, URI_1, mockImageViewTarget());
  TestableBitmapHunter hunter =
      new TestableBitmapHunter(picasso, dispatcher, cache, stats, action, bitmap);

  Bitmap result = hunter.hunt();
  verify(cache).get(URI_KEY_1);
  verify(hunter.requestHandler).load(action.getRequest(), 0);
  assertThat(result).isEqualTo(bitmap);
}
 
Example 41
Project: GitHub   File: BitmapPreFillRunnerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testAllocatesABitmapPerSizeInAllocationOrder() {
  PreFillType size = new PreFillType.Builder(100).setConfig(Bitmap.Config.ARGB_8888).build();
  final int toAdd = 3;
  Map<PreFillType, Integer> allocationOrder = new HashMap<>();
  allocationOrder.put(size, toAdd);
  BitmapPreFillRunner handler = getHandler(allocationOrder);
  handler.run();

  Bitmap expected = Bitmap.createBitmap(size.getWidth(), size.getHeight(), size.getConfig());
  // TODO(b/20335397): This code was relying on Bitmap equality which Robolectric removed
  // assertThat(addedBitmaps).containsExactly(expected, expected, expected);
}
 
Example 42
Project: BookPage   File: CoverPageView.java   Source Code and License 5 votes vote down vote up
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int height = ViewUtils.measureSize(defaultHeight, heightMeasureSpec);
    int width = ViewUtils.measureSize(defaultWidth, widthMeasureSpec);
    setMeasuredDimension(width, height);

    viewWidth = width;
    viewHeight = height;

    previousPage = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.RGB_565);
    currentPage = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.RGB_565);
    nextPage = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.RGB_565);
}
 
Example 43
Project: Android-Music-Player   File: thumbSlider.java   Source Code and License 5 votes vote down vote up
void loadBitmaps(){
    if(Ui.ef.MusicPlayer != null){
        musicPlayer mp = Ui.ef.MusicPlayer;
        final Bitmap bm = audioHandler.getAlubumArtBitmapById(Ui.ef.getContentResolver(),mp.handler.AID);
        if(bm != null){
            Palette palette = Palette.from(bm).generate();
            int color = thumbRing.Color0;
            int newColor = palette.getMutedColor(color);
            if(newColor == color){
                newColor = palette.getVibrantColor(color);
            }
            if(newColor == color){
                newColor = palette.getLightVibrantColor(color);
            }
            threeThumb.ring.img.maskPaint.setColor(newColor);
        }else{
            threeThumb.ring.img.maskPaint.setColor(thumbRing.Color0);
        }

        Ui.ef.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //threeThumb.setImg(bm);
                threeThumb.invalidate();
                threeThumb.ring.invalidate();
            }
        });
    }
}
 
Example 44
Project: BizareChat   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void setUserInformation() {

        View headerView = mNavigationView.getHeaderView(0);
        headerView.findViewById(R.id.nav_header_root).setOnClickListener(this);
        if (currentUser == null) {
            currentUser = CurrentUser.getInstance();
        }

        TextView email = (TextView) headerView.findViewById(R.id.header_email);
        if (currentUser.getCurrentEmail() != null) {
            email.setText(currentUser.getCurrentEmail());
        }

        drawerLogin = (TextView) headerView.findViewById(R.id.user_login);
        drawerLogin.setText(CurrentUser.getInstance().getFullName());

        drawerAvatar = (CircleImageView) headerView.findViewById(R.id.user_pic);
        if (converter == null) {
            converter = new Converter(getApplicationContext());
        }

        String s = CurrentUser.getInstance().getStringAvatar();
        Bitmap bitmap = converter.decodeBase64(s);
        if (bitmap != null) {
            drawerAvatar.setImageBitmap(bitmap);
        }

    }
 
Example 45
Project: ywApplication   File: OnekeyShare.java   Source Code and License 5 votes vote down vote up
/** 设置一个将被截图分享的View , surfaceView是截不了图片的*/
public void setViewToShare(View viewToShare) {
	try {
		Bitmap bm = captureView(viewToShare, viewToShare.getWidth(), viewToShare.getHeight());
		shareParamsMap.put("viewToShare", bm);
	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example 46
Project: Asteroid   File: AsteroidData.java   Source Code and License 5 votes vote down vote up
public AsteroidData(Bitmap asteroidBitmap) {
    this.asteroidBitmap = asteroidBitmap;
    x = (float) Math.random();
    y = -asteroidBitmap.getHeight();
    rotationDiff = (float) Math.random() - 0.5f;
    xDiff = (float) (Math.random() - 0.5) * 0.002f;
    yDiff = (float) (Math.random() * 6) + 1;
}
 
Example 47
Project: RetroMusicPlayer   File: AbsTagEditorActivity.java   Source Code and License 5 votes vote down vote up
protected void setImageBitmap(@Nullable final Bitmap bitmap, int bgColor) {
    if (bitmap == null) {
        image.setImageResource(R.drawable.default_album_art);
    } else {
        image.setImageBitmap(bitmap);
    }
    setColors(bgColor);
}
 
Example 48
Project: betterHotels   File: BlurredLayoutActivity.java   Source Code and License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_blurred_layout);
    initializeToolbar();

    ivNoTrip = (ImageView) findViewById(R.id.iv_no_trip);
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 8;
    Bitmap blurTemplate = BitmapFactory.decodeResource(getResources(), R.drawable.img_city_8);
    ivNoTrip.setImageBitmap(Blur.fastblur(this, ((BitmapDrawable) ivNoTrip.getDrawable()).getBitmap(), 25));
}
 
Example 49
Project: XFrame   File: XBitmapUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 亮度、色相、饱和度处理
 *
 * @param bitmap          原图
 * @param lumValue        亮度值
 * @param hueValue        色相值
 * @param saturationValue 饱和度值
 * @return 亮度、色相、饱和度处理后的图片
 */
public static Bitmap lumAndHueAndSaturation(Bitmap bitmap, int lumValue,
                                            int hueValue, int saturationValue) {
    // 计算出符合要求的饱和度值
    float newSaturationValue = saturationValue * 1.0F / 127;
    // 计算出符合要求的亮度值
    float newlumValue = lumValue * 1.0F / 127;
    // 计算出符合要求的色相值
    float newHueValue = (hueValue - 127) * 1.0F / 127 * 180;

    // 创建一个颜色矩阵并设置其饱和度
    ColorMatrix colorMatrix = new ColorMatrix();

    // 设置饱和度值
    colorMatrix.setSaturation(newSaturationValue);
    // 设置亮度值
    colorMatrix.setScale(newlumValue, newlumValue, newlumValue, 1);
    // 控制让红色区在色轮上旋转的角度
    colorMatrix.setRotate(0, newHueValue);
    // 控制让绿红色区在色轮上旋转的角度
    colorMatrix.setRotate(1, newHueValue);
    // 控制让蓝色区在色轮上旋转的角度
    colorMatrix.setRotate(2, newHueValue);

    // 创建一个画笔并设置其颜色过滤器
    Paint paint = new Paint();
    paint.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
    // 创建一个新的图片并创建画布
    Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(),
            bitmap.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(newBitmap);
    // 将原图使用给定的画笔画到画布上
    canvas.drawBitmap(bitmap, 0, 0, paint);
    return newBitmap;
}
 
Example 50
Project: exciting-app   File: ShareWechat.java   Source Code and License 5 votes vote down vote up
@Override
public void share(Activity activity, Bitmap shareBitmap, Bitmap thumbBitmap, int platform) {
    ShareType = ShareConstant.SHARE;
    this.platform = platform;

    if (activity == null)
        return;

    thumbBitmap = GlideBitmapFactory.decodeFile(savePath);

    if (api == null) {
        api = WXAPIFactory.createWXAPI(activity, BuildConfig.WECHAT_APP_ID, false);
        api.registerApp(BuildConfig.WECHAT_APP_ID);
    }

    WXMediaMessage msg = new WXMediaMessage();
    msg.thumbData = Util.bmpToByteArray(thumbBitmap, true);

    WXImageObject imgObj = new WXImageObject();
    imgObj.setImagePath(savePath);
    msg.mediaObject = imgObj;

    SendMessageToWX.Req req = new SendMessageToWX.Req();
    req.transaction = "img" + System.currentTimeMillis();
    req.message = msg;

    if (platform == ShareConstant.SHARE_MEDIA.WECHAT) {
        req.scene = SendMessageToWX.Req.WXSceneSession;

    } else if (platform == ShareConstant.SHARE_MEDIA.WECHAT_CIRCLE) {
        req.scene = SendMessageToWX.Req.WXSceneTimeline;
    }

    api.sendReq(req);

    if (thumbBitmap != null) {
        thumbBitmap.recycle();
    }

}
 
Example 51
Project: Pluto-Android   File: FinalBitmap.java   Source Code and License 5 votes vote down vote up
/**
 * 网络加载bitmap
 * 
 * @return
 */
private Bitmap processBitmap(String uri, BitmapDisplayConfig config) {
	if (mConfig != null && mConfig.bitmapProcess != null) {
		return mConfig.bitmapProcess.processBitmap(uri, config);
	}
	return null;
}
 
Example 52
Project: SimpleUILauncher   File: Utilities.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a bitmap suitable for the all apps view. The icon is badged for {@param user}.
 * The bitmap is also visually normalized with other icons.
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static Bitmap createBadgedIconBitmap(
        Drawable icon, UserHandleCompat user, Context context) {
    float scale = FeatureFlags.LAUNCHER3_DISABLE_ICON_NORMALIZATION ?
            1 : IconNormalizer.getInstance().getScale(icon, null);
    Bitmap bitmap = createIconBitmap(icon, context, scale);
    return badgeIconForUser(bitmap, user, context);
}
 
Example 53
Project: RLibrary   File: Luban.java   Source Code and License 5 votes vote down vote up
/**
 * 保存图片到指定路径
 * Save image with specified size
 *
 * @param filePath the image file save path 储存路径
 * @param bitmap   the image what be save   目标图片
 * @param size     the file size of image   期望大小
 * @param width    width of thumbnail
 * @param height   height of thumbnail
 */
private File saveImage(String filePath, Bitmap bitmap, long size, int width, int height) {
    checkNotNull(bitmap, TAG + "bitmap cannot be null");

    File result = new File(filePath.substring(0, filePath.lastIndexOf("/")));

    if (!result.exists() && !result.mkdirs()) return null;

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    int options = sQuality;
    bitmap.compress(Bitmap.CompressFormat.JPEG, options, stream);

    while (stream.toByteArray().length / 1024 > size && options > 6) {
        stream.reset();
        options -= 6;
        bitmap.compress(Bitmap.CompressFormat.JPEG, options, stream);
    }
    bitmap.recycle();
    try {
        filePath += "_s_" + width + "x" + height + ".jpg";
        FileOutputStream fos = new FileOutputStream(filePath);
        fos.write(stream.toByteArray());
        fos.flush();
        fos.close();
        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return new File(filePath);
}
 
Example 54
Project: Linphone4Android   File: LinphoneService.java   Source Code and License 5 votes vote down vote up
private synchronized void setIncallIcon(IncallIconState state) {
	if (state == mCurrentIncallIconState) return;
	mCurrentIncallIconState = state;

	int notificationTextId = 0;
	int inconId = 0;
	
	switch (state) {
	case IDLE:
		mNM.cancel(INCALL_NOTIF_ID);
		return;
	case INCALL:
		inconId = R.drawable.topbar_call_notification;
		notificationTextId = R.string.incall_notif_active;
		break;
	case PAUSE:
		inconId = R.drawable.topbar_call_notification;
		notificationTextId = R.string.incall_notif_paused;
		break;
	case VIDEO:
		inconId = R.drawable.topbar_videocall_notification;
		notificationTextId = R.string.incall_notif_video;
		break;	
	default:
		throw new IllegalArgumentException("Unknown state " + state);
	}
	
	if (LinphoneManager.getLc().getCallsNb() == 0) {
		return;
	}
	
	LinphoneCall call = LinphoneManager.getLc().getCalls()[0];
	String userName = call.getRemoteAddress().getUserName();
	String domain = call.getRemoteAddress().getDomain();
	String displayName = call.getRemoteAddress().getDisplayName();
	LinphoneAddress address = LinphoneCoreFactory.instance().createLinphoneAddress(userName,domain,null);
	address.setDisplayName(displayName);

	LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(address);
	Uri pictureUri = contact != null ? contact.getPhotoUri() : null;
	Bitmap bm = null;
	try {
		bm = MediaStore.Images.Media.getBitmap(getContentResolver(), pictureUri);
	} catch (Exception e) {
		bm = BitmapFactory.decodeResource(getResources(), R.drawable.avatar);
	}
	String name = address.getDisplayName() == null ? address.getUserName() : address.getDisplayName();
	mIncallNotif = Compatibility.createInCallNotification(getApplicationContext(), mNotificationTitle, getString(notificationTextId), inconId, bm, name, mNotifContentIntent);

	notifyWrapper(INCALL_NOTIF_ID, mIncallNotif);
}
 
Example 55
Project: tiny   File: BitmapCompressTestActivity.java   Source Code and License 5 votes vote down vote up
private void testStream() {
    try {
        final InputStream is = getResources().getAssets()
                .open("test-4.jpg");
        File outfile = new File(getExternalFilesDir(null), "test-4.jpg");
        FileOutputStream fos = new FileOutputStream(outfile);
        byte[] buffer = new byte[4096];
        int len = -1;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.close();

        InputStream is2 = new FileInputStream(outfile);

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = mConfig;
        Bitmap originBitmap = BitmapFactory.decodeStream(is, null, options);

        setupOriginInfo(originBitmap);

        Tiny.BitmapCompressOptions compressOptions = new Tiny.BitmapCompressOptions();
        compressOptions.config = mConfig;
        Tiny.getInstance().source(is2).asBitmap().withOptions(compressOptions).compress(new BitmapCallback() {
            @Override
            public void callback(boolean isSuccess, Bitmap bitmap) {
                if (!isSuccess) {
                    mCompressTv.setText("compress bitmap failed!");
                    return;
                }
                setupCompressInfo(bitmap);
            }
        });
        is.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 56
Project: chromium-for-android-56-debug-video   File: AppBannerInfoBarAndroid.java   Source Code and License 5 votes vote down vote up
private AppBannerInfoBarAndroid(String appTitle, Bitmap iconBitmap, AppData data) {
    super(0, iconBitmap, appTitle, null, data.installButtonText(), null);
    mAppTitle = appTitle;
    mAppData = data;
    mAppUrl = null;
    mInstallState = INSTALL_STATE_NOT_INSTALLED;
}
 
Example 57
Project: GCSApp   File: EaseLoadLocalBigImgTask.java   Source Code and License 5 votes vote down vote up
@Override
protected void onPostExecute(Bitmap result) {
	super.onPostExecute(result);
	pb.setVisibility(View.INVISIBLE);
	photoView.setVisibility(View.VISIBLE);
	if (result != null)
		EaseImageCache.getInstance().put(path, result);
	else
		result = BitmapFactory.decodeResource(context.getResources(),
				R.drawable.ease_default_image);
	photoView.setImageBitmap(result);
}
 
Example 58
Project: android-project-gallery   File: ImageAutoPlayImageSwitcherActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState)
{
	supportRequestWindowFeature(WindowCompat.FEATURE_ACTION_BAR_OVERLAY);
	super.onCreate(savedInstanceState);
	setContentView(R.layout.wrapper_cn_image_autoplay);

	Intent intent = getIntent();
	mImageList = intent.getStringArrayListExtra(EXTRA_IMAGE_LIST);
	mTitle = intent.getStringExtra(EXTRA_TITLE);
	mCacheDir = intent.getStringExtra(EXTRA_DIRECTORY);
	mPeriod = intent.getIntExtra(EXTRA_PERIOD, SCROLL_PERIOD_DEFAULT);
	mPosition = intent.getIntExtra(EXTRA_POSITION, 0);
	// 默认进行图片缓存
	mCacheOnDisc = intent.getBooleanExtra(EXTRA_CACHE_ON_DISC, true);
	if (mPeriod <= 0)
	{
		mPeriod = SCROLL_PERIOD_DEFAULT;
	}
	if (TextUtils.isEmpty(mCacheDir))
	{
		// 没有地址不进行缓存, 后续看看有没有需要考虑没有地址使用默认地址的情况
		// 原则上, 在设计时, 都提供存储地址应该比较合理
		mCacheOnDisc = false;
	}

	if (TextUtils.isEmpty(mTitle))
	{
		int titleId = getResources().getIdentifier("app_name", "string", this.getPackageName());
		mTitle = getString(titleId);
	}
	getSupportActionBar().show();
	getSupportActionBar().setTitle(mTitle);
	//getSupportActionBar().setSubtitle(title + "sub");
	getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar_bg_translucent));
	
	getUiHandler().postDelayed(new Runnable()
	{

		@Override
		public void run()
		{
			getSupportActionBar().hide();
		}
	}, ACTIONBAR_HIDE_DELAYED);
	
	
	SaveImageOptions saveOptions = new SaveImageOptions.Builder()
		.medule("Image_AutoPlay")
		.extraDir(mCacheDir)
		.build();

	DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder()
		.showImageForEmptyUri(R.drawable.warn_image_empty)
		.showImageOnFail(R.drawable.warn_image_error)
		.cacheInMemory(true)
		.cacheOnDisc(mCacheOnDisc)
		.considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.saveImageOptions(saveOptions)
		.build();

	imageSwitcher = (XImageSwitcher) findViewById(R.id.imageSwitcher);
	imageSwitcher.setFactory(this);
	imageSwitcher.setOnClickListener(this);
	imageSwitcher.addImagePath(mImageList);
	imageSwitcher.setDisplayImageOptions(displayImageOptions);
	imageSwitcher.startAutoScroll(mPeriod, mPosition);
}
 
Example 59
Project: Rey-MusicPlayer   File: SongDataHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Moves the specified cursor to the specified index and populates this
 * helper object with new song data.
 *
 * @param context Context used to get a new Common object.
 * @param index   The index of the song.
 */

public void populateSongData(Context context, ArrayList<Song> songs, int index) {

    mSongHelper = this;
    mApp = (Common) context.getApplicationContext();
    mIndex = index;

    if (songs == null && mApp.isServiceRunning() && mApp.getService() != null) {
        this.setId(mApp.getService().getSongList().get(index)._id);
        this.setTitle(mApp.getService().getSongList().get(index)._title);
        this.setAlbum(mApp.getService().getSongList().get(index)._album);
        this.setArtist(mApp.getService().getSongList().get(index)._artist);
        this.setDuration(mApp.getService().getSongList().get(index)._duration);
        this.setFilePath(mApp.getService().getSongList().get(index)._path);
        this.setAlbumArtPath(String.valueOf(MusicUtils.getAlbumArtUri(mApp.getService().getSongList().get(index)._albumId)));

        Bitmap bitmap = ImageLoader.getInstance().loadImageSync(getAlbumArtPath());
        setAlbumArt(bitmap);
        try {
            int d = Palette.from(bitmap).generate().getDominantColor(Color.parseColor("#FFFFFF"));
            setColor(d);
        } catch (Exception e) {
            setColor(Color.parseColor("#FFFFFF"));
        }
    } else {
        this.setId(songs.get(index)._id);
        this.setTitle(songs.get(index)._title);
        this.setAlbum(songs.get(index)._album);
        this.setArtist(songs.get(index)._artist);
        this.setDuration(songs.get(index)._duration);
        this.setFilePath(songs.get(index)._path);
        this.setAlbumArtPath(String.valueOf(MusicUtils.getAlbumArtUri(songs.get(index)._albumId)));
    }
}
 
Example 60
Project: KTools   File: ImageActivity.java   Source Code and License 5 votes vote down vote up
@OnClick(R.id.btn_screen_capture)
public void onBtnScreenCaptureClicked() {
    View decorView = getWindow().getDecorView();
    decorView.setDrawingCacheEnabled(true);
    decorView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
    decorView.buildDrawingCache();
    Bitmap screen = Bitmap.createBitmap(decorView.getDrawingCache());
    KDialog.showImgInDialog(this, screen);
}