最近研究了一下获取图片倒映的算法及剪切、放缩图片,有点成就,现贡献给大家参考:
1. 获取图片倒映:
public Bitmap getReflectedImage(Bitmap originalImage) { final int reflectionGap = 0; int width = originalImage.getWidth(); int height = originalImage.getHeight(); Matrix matrix = new Matrix(); matrix.preScale(1, -1); Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height / 2, width, height / 2, matrix, false); Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888); Canvas canvas = new Canvas(bitmapWithReflection); canvas.drawBitmap(originalImage, 0, 0, null); Paint defaultPaint = new Paint(); canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint); canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null); Paint paint = new Paint(); LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP); paint.setShader(shader); paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint); defaultPaint.setColor(Color.LTGRAY); width--; try { if (!originalImage.isRecycled()) originalImage.recycle(); } catch (Exception e) { Log.e(tag, e.getMessage(), e); } return bitmapWithReflection; }
2. 剪切图片:
private Bitmap cutImage(Bitmap oldBitmap){ Bitmap newBitmap = Bitmap.createBitmap(oldBitmap, 0, 0, oldBitmap.getHeight() / 2, oldBitmap.getWidth() / 2); return newBitmap; }
3. 放缩图片:
a. 指定大小放缩图片
private Bitmap scaleImage(Bitmap bmSrc){ Matrix matrix=new Matrix(); matrix.postScale((float)0.5,(float)0.5); Bitmap bmTarget=Bitmap.createBitmap(bmSrc, 0, 0, bmSrc.getWidth(), bmSrc.getHeight(), matrix, true); return bmTarget; }
b. 指定大小范围放缩图片
public Bitmap getImgBitmap(File f, int size){ //图片文件 FileInputStream fis1=null; Bitmap bm=null; try { fis1=new FileInputStream(f); //Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(fis1,null,o); //The new size we want to scale to final int REQUIRED_SIZE=size; //Find the correct scale value. It should be the power of 2. int width_tmp=o.outWidth, height_tmp=o.outHeight; if (width_tmp < size){ FileInputStream fis2=new FileInputStream(f); bm=BitmapFactory.decodeStream(fis2); fis2.close(); return bm; } int scale=1; while(true){ if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE) break; width_tmp/=2; height_tmp/=2; scale++; } //Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize=scale; FileInputStream fis3=new FileInputStream(f); bm=BitmapFactory.decodeStream(fis3, null, o2); fis3.close(); return bm; } catch (Exception e) { Log.e(tag, e.getMessage(), e); return BitmapFactory.decodeResource(context.getResources(), R.drawable.icon); } finally{ try { fis1.close(); } catch (IOException e) { Log.e(tag, e.getMessage(), e); } } }