public static Bitmap rotateImage(String path, Bitmap bm) { int orientation = 1; try { ExifInterface exifJpeg = new ExifInterface(path); orientation = exifJpeg.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); //// orientation = Integer.parseInt(exifJpeg.getAttribute(ExifInterface.TAG_ORIENTATION)); } catch (IOException e) { e.printStackTrace(); } if (orientation != ExifInterface.ORIENTATION_NORMAL) { int width = bm.getWidth(); int height = bm.getHeight(); Matrix matrix = new Matrix(); if (orientation == ExifInterface.ORIENTATION_ROTATE_90) { matrix.postRotate(90); } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) { matrix.postRotate(180); } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) { matrix.postRotate(270); } return Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true); } return bm; }
/** * 将图片转化为圆形头像 @Title: toRoundBitmap * * @throws */ public static Bitmap toRoundBitmap(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); float roundPx; float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom; if (width <= height) { roundPx = width / 2; left = 0; top = 0; right = width; bottom = width; height = width; dst_left = 0; dst_top = 0; dst_right = width; dst_bottom = width; } else { roundPx = height / 2; float clip = (width - height) / 2; left = clip; right = width - clip; top = 0; bottom = height; width = height; dst_left = 0; dst_top = 0; dst_right = height; dst_bottom = height; } Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888); Canvas canvas = new Canvas(output); final Paint paint = new Paint(); final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom); final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom); final RectF rectF = new RectF(dst); paint.setAntiAlias(true); // 设置画笔无锯齿 canvas.drawARGB(0, 0, 0, 0); // 填充整个Canvas // 以下有两种方法画圆,drawRounRect和drawCircle canvas.drawRoundRect( rectF, roundPx, roundPx, paint); // 画圆角矩形,第一个参数为图形显示区域,第二个参数和第三个参数分别是水平圆角半径和垂直圆角半径。 // canvas.drawCircle(roundPx, roundPx, roundPx, paint); paint.setXfermode( new PorterDuffXfermode( Mode.SRC_IN)); // 设置两张图片相交时的模式,参考http://trylovecatch.iteye.com/blog/1189452 canvas.drawBitmap(bitmap, src, dst, paint); // 以Mode.SRC_IN模式合并bitmap和已经draw了的Circle return output; }
/** * @param options - BitmapFactory.Options with out* options populated * @return Bitmap that case be used for inBitmap */ protected Bitmap getBitmapFromReusableSet(BitmapFactory.Options options) { // BEGIN_INCLUDE(get_bitmap_from_reusable_set) Bitmap bitmap = null; if (mReusableBitmaps != null && !mReusableBitmaps.isEmpty()) { synchronized (mReusableBitmaps) { final Iterator<SoftReference<Bitmap>> iterator = mReusableBitmaps.iterator(); Bitmap item; while (iterator.hasNext()) { item = iterator.next().get(); if (null != item && item.isMutable()) { // Check to see it the item can be used for inBitmap if (canUseForInBitmap(item, options)) { bitmap = item; // Remove from reusable set so it can't be used // again iterator.remove(); break; } } else { // Remove from the set if the reference has been // cleared. iterator.remove(); } } } } return bitmap; // END_INCLUDE(get_bitmap_from_reusable_set) }
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(); } }
private void performDecode(DecodeTask currentDecodeTask) throws IOException { if (isTaskDead(currentDecodeTask)) { Log.d(DECODE_SERVICE, "Skipping decode task for page " + currentDecodeTask.pageNumber); return; } Log.d(DECODE_SERVICE, "Starting decode of page: " + currentDecodeTask.pageNumber); CodecPage vuPage = getPage(currentDecodeTask.pageNumber); preloadNextPage(currentDecodeTask.pageNumber); if (isTaskDead(currentDecodeTask)) { return; } Log.d(DECODE_SERVICE, "Start converting map to bitmap"); float scale = calculateScale(vuPage) * currentDecodeTask.zoom; final Bitmap bitmap = vuPage.renderBitmap( getScaledWidth(currentDecodeTask, vuPage, scale), getScaledHeight(currentDecodeTask, vuPage, scale), currentDecodeTask.pageSliceBounds); Log.d(DECODE_SERVICE, "Converting map to bitmap finished"); if (isTaskDead(currentDecodeTask)) { bitmap.recycle(); return; } finishDecoding(currentDecodeTask, bitmap); }
public void setBitmap() { mBitmapWidth = mBitmap.getWidth(); mBitmapHeight = mBitmap.getHeight(); mRadius = (int) (mBitmapWidth / 2); mBitmapNewHeight = (int) Math.round((double) mRadius * Math.sin(Math.PI / (double) mNumberOfMirrors)); if (mBitmapNewHeight > mBitmapHeight) { mBitmapNewHeight = mBitmapHeight / 2; mRadius = (int) Math.round((double) mBitmapNewHeight / Math.sin(Math.PI / (double) mNumberOfMirrors)); } mScale = (float) mBitmapViewWidth / mRadius; // Log.i(TAG,String.format("%d", mBitmapViewWidth)); mBitmapViewHeight = Math.round((float) mBitmapNewHeight * mScale); mScaledHeight = (int) (mScale * mBitmapHeight); mScaledWidth = (int) (mScale * mBitmapWidth); // Log.i(TAG,String.format("%d %d", mRadius, mBitmapNewHeight)); mAlphaMark = false; mViewBitmap = Bitmap.createBitmap(mBitmapViewWidth, mBitmapViewHeight, Bitmap.Config.ARGB_8888); mX = mScaledWidth - mBitmapViewWidth; mY = mScaledHeight - mBitmapViewHeight; mCurX = (int) (Math.random() * mX / mScale); mCurY = (int) (Math.random() * mY / mScale); mAlpha = mBitmap.hasAlpha(); // Toast.makeText(mContext, Boolean.toString(mAlpha), // Toast.LENGTH_SHORT) // .show(); }
@Override public void handleMessage(Message message) { switch (message.what) { case ZXING_RESTART: restartPreviewAndDecode(); break; case R.id.zxing_decode_succeeded: state = State.SUCCESS; Bundle bundle = message.getData(); Bitmap barcode = null; if (bundle != null) { byte[] compressedBitmap = bundle.getByteArray(DecodeThread.BARCODE_BITMAP); if (compressedBitmap != null) { barcode = BitmapFactory.decodeByteArray(compressedBitmap, 0, compressedBitmap.length, null); // Mutable copy: barcode = barcode.copy(Bitmap.Config.ARGB_8888, true); } } activity.handleDecode((Result) message.obj, barcode); break; case R.id.zxing_decode_failed: // We're decoding as fast as possible, so when one decode fails, start another. state = State.PREVIEW; cameraManager.requestPreviewFrame(decodeThread.getHandler(), R.id.zxing_decode); break; } }
public String saveImage(Uri image, int width, int height) { String imagePath = null; try { byte[] data = readFileThroughUri(image); BitmapFactory.Options options = new BitmapFactory.Options(); options.outWidth = height; options.outHeight = width; options.inSampleSize = 2; Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length, options); Bitmap scaledBmp = Bitmap.createScaledBitmap(bmp, width, height, false); bmp.recycle(); bmp = null; ByteArrayOutputStream bytes = new ByteArrayOutputStream(); scaledBmp.compress( Bitmap.CompressFormat.JPEG, (int) (100 * ImageFileManipulation.IAMGE_COMPRESSION_RATIO), bytes); imagePath = ImageFileManipulation.EXTERNAL_MEMORY + getFileName() + ".jpeg"; boolean isFileCreate = createFileInData(imagePath, bytes.toByteArray()); if (!isFileCreate) // if file is not created return null return null; } catch (Exception e) { e.printStackTrace(); } return imagePath; }
/** 设置Matrix, 强制刷新 */ private void transformDraw() { if (mWaterMarkBitmap == null) return; int bitmapWidth = (int) (mWaterMarkBitmap.getWidth() * mScale); int bitmapHeight = (int) (mWaterMarkBitmap.getHeight() * mScale); // computeRect(-framePadding + (int)mCenterPoint.x, -framePadding + (int)mCenterPoint.y, // bitmapWidth + framePadding + (int)mCenterPoint.x, bitmapHeight + framePadding + // (int)mCenterPoint.y, mDegree); computeRect( (int) mCenterPoint.x - bitmapWidth / 2 - framePadding, (int) mCenterPoint.y - bitmapHeight / 2 - framePadding, (int) mCenterPoint.x + bitmapWidth / 2 + framePadding, (int) mCenterPoint.y + bitmapHeight / 2 + framePadding, mDegree); // 设置缩放比例 matrix.setScale(mScale, mScale); // 绕着图片中心进行旋转 matrix.postRotate(mDegree % 360, bitmapWidth / 2, bitmapHeight / 2); // 设置画该图片的起始点 matrix.postTranslate( mCenterPoint.x - (offsetX + bitmapWidth / 2), mCenterPoint.y - (offsetY + bitmapHeight / 2)); invalidate(); }
public void doStart() { synchronized (sh) { /* * DisplayMetrics metrics = new DisplayMetrics(); ((Activity) * ctx * ).getWindowManager().getDefaultDisplay().getMetrics(metrics); * int width = metrics.widthPixels; int height = * metrics.heightPixels; */ // Create World and set drag Vector2 drag = new Vector2(0, 10); world = new GameEngine(drag, ctx, surfaceWidth, surfaceHeight, (float) 640); // Start getting dt frameStart = (float) System.nanoTime() / 1000000000.0f; // init the main character; Bitmap pict = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.ball); Vector2 posC = new Vector2(150, 300); ball = new PhysicObject(posC, pict, "player"); c1 = new Circle(posC, 25, (pict.getWidth() / 2), (pict.getHeight() / 2)); ball.AddCircle(c1); world.SetPlayer(ball); // Vector2 otherpos = new Vector2(200, 300); // world.AddTree(otherpos); } }
@SuppressWarnings("unused") public Bitmap getThumbnail(Uri uri, int THUMBNAIL_SIZE) throws FileNotFoundException, IOException { InputStream input = context.getContentResolver().openInputStream(uri); BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options(); onlyBoundsOptions.inJustDecodeBounds = true; onlyBoundsOptions.inDither = true; // optional onlyBoundsOptions.inPreferredConfig = Config.ARGB_8888; // optional BitmapFactory.decodeStream(input, null, onlyBoundsOptions); input.close(); if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1)) return null; int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth; double ratio = (originalSize > THUMBNAIL_SIZE) ? (originalSize / THUMBNAIL_SIZE) : 1.0; BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio); bitmapOptions.inDither = true; // optional bitmapOptions.inPreferredConfig = Config.ARGB_8888; // optional input = context.getContentResolver().openInputStream(uri); Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions); int width = bitmap.getWidth(); int height = bitmap.getHeight(); input.close(); return bitmap; }
public boolean loadFromUri(Uri uri) { ParcelFileDescriptor parcelFileDescriptor = null; try { parcelFileDescriptor = Base.activity.getContentResolver().openFileDescriptor(uri, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); copyBitmap(BitmapFactory.decodeFileDescriptor(fileDescriptor)); parcelFileDescriptor.close(); parcelFileDescriptor = null; if (_Source != null) { _BitmapRect = new Rect(0, 0, _Source.getWidth(), _Source.getHeight()); } } catch (FileNotFoundException fnfE) { return false; } catch (IOException ioE) { return false; } catch (Exception e) { return false; } if (parcelFileDescriptor != null) { try { parcelFileDescriptor.close(); } catch (IOException e) { return false; } } return true; }
// 裁剪解决方案---(根据Bitmap图片压缩) public static Bitmap createScaledBitmap( Bitmap unscaledBitmap, int dstWidth, int dstHeight, ScalingLogic scalingLogic) { Rect srcRect = calculateSrcRect( unscaledBitmap.getWidth(), unscaledBitmap.getHeight(), dstWidth, dstHeight, scalingLogic); Rect dstRect = calculateDstRect( unscaledBitmap.getWidth(), unscaledBitmap.getHeight(), dstWidth, dstHeight, scalingLogic); Bitmap scaledBitmap = Bitmap.createBitmap(dstRect.width(), dstRect.height(), Config.RGB_565); Canvas canvas = new Canvas(scaledBitmap); canvas.drawBitmap(unscaledBitmap, srcRect, dstRect, new Paint(Paint.FILTER_BITMAP_FLAG)); return scaledBitmap; }
// 同比缩放解决方案---图片按比例大小压缩方法(根据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); // 压缩好比例大小后再进行质量压缩 }
public static Bitmap bitmap(@Nonnull final String content, final int size) { try { final Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>(); hints.put(EncodeHintType.MARGIN, 0); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); final BitMatrix result = QR_CODE_WRITER.encode(content, BarcodeFormat.QR_CODE, size, size, hints); final int width = result.getWidth(); final int height = result.getHeight(); final int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { final int offset = y * width; for (int x = 0; x < width; x++) { pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.TRANSPARENT; } } final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } catch (final WriterException x) { log.info("problem creating qr code", x); return null; } }
public static Shadow generateShadow(View view, float elevation) { if (!software && renderScript == null) { try { renderScript = RenderScript.create(view.getContext()); blurShader = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript)); } catch (RSRuntimeException ignore) { software = true; } } CornerView cornerView = (CornerView) view; int e = (int) Math.ceil(elevation); int c = Math.max(e, cornerView.getCornerRadius()); Bitmap bitmap; bitmap = Bitmap.createBitmap(e * 2 + 2 * c + 1, e * 2 + 2 * c + 1, Bitmap.Config.ARGB_8888); Canvas shadowCanvas = new Canvas(bitmap); paint.setStyle(Paint.Style.FILL); paint.setColor(0xff000000); roundRect.set(e, e, bitmap.getWidth() - e, bitmap.getHeight() - e); shadowCanvas.drawRoundRect(roundRect, c, c, paint); blur(bitmap, elevation / 2); return new NinePatchShadow(bitmap, elevation, c); }
protected void drawResultPoints(Bitmap barcode, Result rawResult) { ResultPoint[] points = rawResult.getResultPoints(); if (points != null && points.length > 0) { Canvas canvas = new Canvas(barcode); Paint paint = new Paint(); paint.setColor(getResources().getColor(R.color.result_image_border)); paint.setStrokeWidth(3.0f); paint.setStyle(Paint.Style.STROKE); Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2); canvas.drawRect(border, paint); paint.setColor(getResources().getColor(R.color.result_points)); if (points.length == 2) { paint.setStrokeWidth(4.0f); drawLine(canvas, paint, points[0], points[1]); } else if (points.length == 4 && (rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A || rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) { // Hacky special case -- draw two lines, for the barcode and // metadata drawLine(canvas, paint, points[0], points[1]); drawLine(canvas, paint, points[2], points[3]); } else { paint.setStrokeWidth(10.0f); for (ResultPoint point : points) { canvas.drawPoint(point.getX(), point.getY(), paint); } } } }
private void initView(Context context) { mPaint = new Paint(); mPaint.setColor(Color.WHITE); Resources resources = context.getResources(); // get viewConfiguration mClickTimeout = ViewConfiguration.getPressedStateDuration() + ViewConfiguration.getTapTimeout(); mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); // get Bitmap mBottom = BitmapFactory.decodeResource(resources, R.drawable.bottom); mBtnPressed = BitmapFactory.decodeResource(resources, R.drawable.btn_pressed); mBtnNormal = BitmapFactory.decodeResource(resources, R.drawable.btn_unpressed); mFrame = BitmapFactory.decodeResource(resources, R.drawable.frame); mMask = BitmapFactory.decodeResource(resources, R.drawable.mask); mCurBtnPic = mBtnNormal; mBtnWidth = mBtnPressed.getWidth(); mMaskWidth = mMask.getWidth(); mMaskHeight = mMask.getHeight(); mBtnOffPos = mBtnWidth / 2; mBtnOnPos = mMaskWidth - mBtnWidth / 2; mBtnPos = mChecked ? mBtnOnPos : mBtnOffPos; mRealPos = getRealPos(mBtnPos); final float density = getResources().getDisplayMetrics().density; mVelocity = (int) (VELOCITY * density + 0.5f); mExtendOffsetY = (int) (EXTENDED_OFFSET_Y * density + 0.5f); mSaveLayerRectF = new RectF(0, mExtendOffsetY, mMask.getWidth(), mMask.getHeight() + mExtendOffsetY); mXfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN); }
private Bitmap getBitmapFromDrawable(Drawable drawable) { if (drawable == null) { return null; } if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } try { Bitmap bitmap; if (drawable instanceof ColorDrawable) { bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG); } else { bitmap = Bitmap.createBitmap( drawable.getIntrinsicWidth() + 1, drawable.getIntrinsicHeight() + 1, BITMAP_CONFIG); } Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } catch (OutOfMemoryError e) { return null; } }
public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub switch (event.getAction()) { case MotionEvent.ACTION_MOVE: nowX = event.getX(); break; case MotionEvent.ACTION_DOWN: if (event.getX() > bg_on.getWidth() || event.getY() > bg_on.getHeight()) { return false; } onSlip = true; downX = event.getX(); nowX = downX; break; case MotionEvent.ACTION_UP: onSlip = false; boolean lastChoose = nowChoose; if (event.getX() >= (bg_on.getWidth() / 2)) { nowChoose = true; } else { nowChoose = false; } if (isChgLsnOn && (lastChoose != nowChoose)) { ChgLsn.OnChanged(nowChoose); } break; default: break; } invalidate(); return true; }
private Bitmap createBitmap(String content, final int size) { final Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>(); hints.put(EncodeHintType.MARGIN, 0); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); BitMatrix result; try { result = sQRCodeWriter.encode(content, BarcodeFormat.QR_CODE, size, size, hints); } catch (WriterException ex) { mLogger.warn("qr encoder failed: " + ex.toString()); return null; } final int width = result.getWidth(); final int height = result.getHeight(); final int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { final int offset = y * width; for (int x = 0; x < width; x++) { pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.TRANSPARENT; } } final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; }
// ============================================================================== public final int[] renderGlyph( char glyph, Paint paint, android.graphics.Matrix matrix, Rect bounds) { Path p = new Path(); paint.getTextPath(String.valueOf(glyph), 0, 1, 0.0f, 0.0f, p); RectF boundsF = new RectF(); p.computeBounds(boundsF, true); matrix.mapRect(boundsF); boundsF.roundOut(bounds); bounds.left--; bounds.right++; final int w = bounds.width(); final int h = bounds.height(); Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(bm); matrix.postTranslate(-bounds.left, -bounds.top); c.setMatrix(matrix); c.drawPath(p, paint); final int sizeNeeded = w * h; if (cachedRenderArray.length < sizeNeeded) cachedRenderArray = new int[sizeNeeded]; bm.getPixels(cachedRenderArray, 0, w, 0, 0, w, h); bm.recycle(); return cachedRenderArray; }
private void proofLeft(float x, float y) { float h = x - radius; // 取xy点和圆点 的三角形宽 float h2 = h * h; float w = y - radius; // 取xy点和圆点 的三角形长 float w2 = w * w; float distance = (float) Math.sqrt((h2 + w2)); // 勾股定理求 斜边距离 if (distance > radius) { // 如果斜边距离大于半径,则取点和圆最近的一个点为x,y float maxX = x - radius; float maxY = y - radius; x = ((radius * maxX) / distance) + radius; // 通过三角形一边平行原理求出x,y y = ((radius * maxY) / distance) + radius; } if (x < 0) { iconPoint.x = 0; } else if (x > (imageBitmap.getWidth())) { iconPoint.x = imageBitmap.getWidth(); } else { iconPoint.x = x; } if (y < 0) { iconPoint.y = 0; } else if (y > (imageBitmap.getHeight())) { iconPoint.y = imageBitmap.getHeight(); } else { iconPoint.y = y; } isMove = true; }
private static Drawable loadDrawableFromStream( Context context, String url, String filename, int targetWidth, int targetHeight) { prepareResources(context); // Log.v(Constants.LOGTAG,targetWidth); // Log.v(Constants.LOGTAG,targetHeight); try { Options o = new Options(); o.inJustDecodeBounds = true; FileInputStream stream = new FileInputStream(filename); BitmapFactory.decodeStream(stream, null, o); stream.close(); stream = new FileInputStream(filename); int scale = 0; while ((o.outWidth >> scale) > targetWidth || (o.outHeight >> scale) > targetHeight) { Log.v(Constants.LOGTAG, "downsampling"); scale++; } o = new Options(); o.inSampleSize = 1 << scale; Bitmap bitmap = BitmapFactory.decodeStream(stream, null, o); if (Constants.LOG_ENABLED) Log.i( Constants.LOGTAG, String.format("Loaded bitmap (%dx%d).", bitmap.getWidth(), bitmap.getHeight())); BitmapDrawable bd = new BitmapDrawable(mResources, bitmap); return new ZombieDrawable(url, bd); } catch (IOException e) { return null; } }
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(); }
@Test public void shouldCopyBitmap() { Bitmap bitmap = Shadow.newInstanceOf(Bitmap.class); Bitmap bitmapCopy = bitmap.copy(Config.ARGB_8888, true); assertThat(shadowOf(bitmapCopy).getConfig()).isEqualTo(Config.ARGB_8888); assertThat(shadowOf(bitmapCopy).isMutable()).isTrue(); }
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); // 压缩好比例大小后再进行质量压缩 }
protected Bitmap createQrCodeBitmap(String input, int size) { Log.d(Config.LOGTAG, "qr code requested size: " + size); try { final QRCodeWriter QR_CODE_WRITER = new QRCodeWriter(); final Hashtable<EncodeHintType, Object> hints = new Hashtable<>(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); final BitMatrix result = QR_CODE_WRITER.encode(input, BarcodeFormat.QR_CODE, size, size, hints); final int width = result.getWidth(); final int height = result.getHeight(); final int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { final int offset = y * width; for (int x = 0; x < width; x++) { pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.TRANSPARENT; } } final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Log.d(Config.LOGTAG, "output size: " + width + "x" + height); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } catch (final WriterException e) { return null; } }
/** * 重叠合并两张图片,合并后的大小等同于作为底图的图片大小 * * @param background:下层图,即底图 * @param foreground:上层图,即前置图 * @return 合并后的Bitmap */ public static Bitmap toConformBitmap(Bitmap background, Bitmap foreground, Paint paint) { if (null == background) { return null; } int bgWidth = background.getWidth(); int bgHeight = background.getHeight(); // int fgWidth = foreground.getWidth(); // int fgHeight = foreground.getHeight(); // create the new blank bitmap 创建一个新的和SRC长度宽度一样的位图 Bitmap newbmp = null; try { newbmp = Bitmap.createBitmap(bgWidth, bgHeight, Config.ARGB_8888); } catch (OutOfMemoryError e) { // OOM,return null return null; } Canvas cv = new Canvas(newbmp); // draw bg into cv.drawBitmap(background, 0, 0, paint); // 在 0,0坐标开始画入bg // draw fg into if (null != foreground) { cv.drawBitmap(foreground, 0, 0, paint); // 在 0,0坐标开始画入fg ,可以从任意位置画入 } // save all clip cv.save(Canvas.ALL_SAVE_FLAG); // 保存 // store cv.restore(); // 存储 return newbmp; }
@Override public void run() { int w = getWidth(); int h = getHeight(); float wipeArea = 0; float totalArea = w * h; Bitmap bitmap = mBitmap; int[] mPixels = new int[w * h]; // 获取bitmap的所有像素信息 bitmap.getPixels(mPixels, 0, w, 0, 0, w, h); for (int i = 0; i < w; i++) for (int j = 0; j < h; j++) { int index = i + j * w; if (mPixels[index] == 0) { wipeArea++; } } // 计算已扫区域所占的比例 if (wipeArea > 0 && totalArea > 0) { int percent = (int) (wipeArea * 100 / totalArea); Log.v("czm", "percent=" + percent); if (percent > 70) { // 清除图层区域 mCompleted = true; postInvalidate(); } } };