Android Bitmap Detailed Introduction _android

Source: Internet
Author: User
Tags clear screen
Copy Code code as follows:

Package Com.testbitmapscale;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.util.Iterator;
Import com.testbitmapscale.r.drawable;
Import android.app.Activity;
Import Android.graphics.Bitmap;
Import Android.graphics.Bitmap.Config;
Import Android.graphics.BitmapFactory;
Import Android.graphics.Canvas;
Import Android.graphics.Matrix;
Import Android.graphics.Paint;
Import Android.graphics.PorterDuff.Mode;
Import Android.graphics.PorterDuffXfermode;
Import Android.graphics.Rect;
Import Android.graphics.RectF;
Import android.graphics.drawable.BitmapDrawable;
Import android.graphics.drawable.Drawable;
Import Android.media.ThumbnailUtils;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.view.View;
Import Android.widget.ImageView;
Method:
1 Generate rounded corner bitmap picture
2 Generating bitmap shrink graphs
3 Compressed Picture field width and kb
Attention:
The code above, it's best to comment out the rest of the code when testing one of the methods
public class Mainactivity extends activity {
Private ImageView ImageView;
Private Bitmap CopyRawBitmap1;
Private Bitmap copyRawBitmap2;
Private Bitmap copyRawBitmap3;
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
ImageView = (ImageView) Findviewbyid (R.id.imageview);
The first way: get a picture from a resource file
Bitmap Rawbitmap = Bitmapfactory.decoderesource (Getresources (), R.drawable.haha);
Copyrawbitmap1=rawbitmap;
Copyrawbitmap2=rawbitmap;
Copyrawbitmap3=rawbitmap;
The second way: Get the picture from the SD card (Method 1)
String sdcarepath=environment.getexternalstoragedirectory (). toString ();
String filepath=sdcarepath+ "/" + "haha.jpg";
Bitmap RawBitmap1 = bitmapfactory.decodefile (FilePath, NULL);
The second way: Get the picture from the SD card (Method 2)
InputStream Inputstream=getbitmapinputstreamfromsdcard ("haha.jpg");
Bitmap rawBitmap2 = Bitmapfactory.decodestream (InputStream);

———— > Below are the rounded corners that will set the picture
Bitmap Roundcornerbitmap=this.toroundcorner (Rawbitmap, 40);
Imageview.setimagebitmap (ROUNDCORNERBITMAP);
———— > above to set the rounded corners of the picture

———— > below to compress a picture's height and width kb
Get the original high width of the picture
int rawheight = Rawbitmap.getheight ();
int rawwidth = Rawbitmap.getwidth ();
Set the new high width of the picture
int newheight = 500;
int newwidth = 500;
Calculate scaling factor
float Heightscale = ((float) newheight)/rawheight;
float Widthscale = ((float) newwidth)/rawwidth;
New Build Matrix
Matrix matrix = new Matrix ();
Matrix.postscale (Heightscale, Widthscale);
Set the rotation angle of a picture
Matrix.postrotate (-30);
Set the tilt of a picture
Matrix.postskew (0.1f, 0.1f);
Compress picture size
The width and height of the picture and the KB size change after compression
Bitmap Newbitmap = Bitmap.createbitmap (rawbitmap, 0, 0, rawwidth,rawwidth, Matrix, True);
Convert Bitmap to Drawable
drawable newbitmapdrawable = new bitmapdrawable (NEWBITMAP);
Imageview.setimagedrawable (newbitmapdrawable);
The bitmap is then saved to the SDcard to facilitate comparison of the original image.
This.compressandsavebitmaptosdcard (Newbitmap, "xx100.jpg", 80);
Problem:
Original size is 625x690 90.2kB
If you set the picture 500x500 compression size is 171kB. That is, the KB becomes larger after compression.
The reason is to be: compress (Bitmap.CompressFormat.JPEG, quality, fileoutputstream);
The second parameter quality is set somewhat larger (for example, 100).
Commonly used is 80, just set 100 too big caused.
———— > above to compress a picture's height and width kb


———— > below for the KB compression of the picture, width and height unchanged
This.compressandsavebitmaptosdcard (CopyRawBitmap1, "0011fa.jpg", 80);
———— > above for the KB compression of the picture, the width and height unchanged

———— > Below is a thumbnail method for obtaining an SD card picture 1
String sdcarepath1=environment.getexternalstoragedirectory (). toString ();
String filepath1=sdcarepath1+ "/" + "haha.jpg";
Bitmap Bitmapthumbnail1=this.getbitmapthumbnail (FILEPATH1);
Imageview.setimagebitmap (BITMAPTHUMBNAIL1);
———— > above for access to the SD card picture thumbnail Method 1

———— > Below is a thumbnail method for obtaining an SD card picture 2
String sdcarepath2=environment.getexternalstoragedirectory (). toString ();
String filepath2=sdcarepath2+ "/" + "haha.jpg";
Bitmap Tempbitmap=bitmapfactory.decodefile (filePath2);
Bitmap Bitmapthumbnail2=thumbnailutils.extractthumbnail (tempbitmap, 100, 100);
Imageview.setimagebitmap (BITMAPTHUMBNAIL2);
———— > above for access to the SD card picture thumbnail Method 2

}
Read the picture under the SD card
Private InputStream Getbitmapinputstreamfromsdcard (String fileName) {
if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {
String sdcarepath=environment.getexternalstoragedirectory (). toString ();
String Filepath=sdcarepath+file.separator+filename;
File File=new file (FilePath);
try {
FileInputStream fileinputstream=new fileinputstream (file);
return fileinputstream;
catch (Exception e) {
E.printstacktrace ();
}

}
return null;
}


To get SDcard directory path functionality
Private String Getsdcardpath () {
String sdcardpath = null;
To determine whether SDcard exists
Boolean issdcardexist = Environment.getexternalstoragestate (). Equals (Android.os.Environment.MEDIA_MOUNTED);
if (issdcardexist) {
Sdcardpath = Environment.getexternalstoragedirectory (). toString ();
}
return sdcardpath;
}
Compress and save pictures to SDcard
private void Compressandsavebitmaptosdcard (Bitmap rawbitmap,string filename,int quality) {
String Savefilepaht=this.getsdcardpath () +file.separator+filename;
File Savefile=new file (savefilepaht);
if (!savefile.exists ()) {
try {
Savefile.createnewfile ();
FileOutputStream fileoutputstream=new FileOutputStream (savefile);
if (fileoutputstream!=null) {
Imagebitmap.compress (format, quality, stream);
Writes the compressed information of the bitmap to a specified output stream
The first parameter format is a compressed format
The second parameter quality is the value of the image compression ratio, 0-100.0 means small size compression, 100 means high quality compression
The third argument stream is the output stream
Rawbitmap.compress (Bitmap.CompressFormat.JPEG, quality, fileoutputstream);
}
Fileoutputstream.flush ();
Fileoutputstream.close ();
catch (IOException e) {
E.printstacktrace ();

}
}
}

Get thumbnails of pictures
Private Bitmap Getbitmapthumbnail (String filePath) {
Bitmapfactory.options options=new bitmapfactory.options ();
True then the actual bitmap object will not be returned, no memory space allocated to it, but some decoding boundary information, such as picture size, can be obtained.
Options.injustdecodebounds=true;
Rawbitmap is null at this time
Bitmap Rawbitmap = Bitmapfactory.decodefile (FilePath, Options);
if (rawbitmap==null) {
System.out.println ("Rawbitmap is null at this time");
}
Insamplesize indicates that the thumbnail size is a fraction of the size of the original picture, if the value is 3
The width and height of the extracted thumbnail are 1/3 of the original picture, and the picture size is 1/9 of the original size.
Calculate samplesize
int samplesize=computesamplesize (options, 150, 200*200);
In order to read the picture, you must set the Options.injustdecodebounds back to False
Options.injustdecodebounds = false;
Options.insamplesize = samplesize;
Original size is 625x690 90.2kB
Test call Computesamplesize (options, 100, 200*100);
Get samplesize=8
Get wide and high, 79 and 87.
79*8=632 87*8=696
Bitmap thumbnailbitmap=bitmapfactory.decodefile (FilePath, Options);
Save to SD card for easy comparison
This.compressandsavebitmaptosdcard (Thumbnailbitmap, "15.jpg", 80);
return thumbnailbitmap;
}

Resources:
http://my.csdn.net/zljk000/code/detail/18212
First parameter: Original Bitmap options
Second parameter: the smaller value of the wide high school for the thumbnail you want to generate
Third parameter: The total pixel of the indent graph that you want to generate
public static int computesamplesize (bitmapfactory.options options,int minsidelength, int maxnumofpixels) {
int initialsize = computeinitialsamplesize (options, minsidelength,maxnumofpixels);
int roundedsize;
if (initialsize <= 8) {
Roundedsize = 1;
while (Roundedsize < initialsize) {
Roundedsize <<= 1;
}
} else {
Roundedsize = (initialsize + 7)/8 * 8;
}
return roundedsize;
}

private static int computeinitialsamplesize (bitmapfactory.options options,int minsidelength, int maxnumofpixels) {
The width of the original picture
Double w = options.outwidth;
The height of the original picture
Double h = options.outheight;
System.out.println ("========== w=" +w+ ", h=" +h);
int lowerbound = (Maxnumofpixels = = 1)? 1: (int) Math.ceil (Math
. sqrt (w * h/maxnumofpixels));
int upperbound = (Minsidelength = = 1)? 128: (int) Math.min (
Math.floor (W/minsidelength), Math.floor (h/minsidelength));
if (Upperbound < lowerbound) {
Return the larger one when there is no overlapping zone.
return lowerbound;
}
if ((maxnumofpixels = = 1) && (minsidelength = = 1)) {
return 1;
else if (minsidelength = = 1) {
return lowerbound;
} else {
return upperbound;
}
}

/**
* @param bitmap need to modify the picture
* @param the radian of the pixels fillet
* @return Fillet picture
*/
Resources:
http://blog.csdn.net/c8822882/article/details/6906768
Public Bitmap Toroundcorner (Bitmap Bitmap, int pixels) {
Bitmap Roundcornerbitmap = Bitmap.createbitmap (Bitmap.getwidth (), Bitmap.getheight (), config.argb_8888);
Canvas Canvas = new Canvas (ROUNDCORNERBITMAP);
int color = 0xff424242;//int color = 0xff424242;
Paint Paint = new Paint ();
Paint.setcolor (color);
Prevent sawtooth
Paint.setantialias (TRUE);
Rect Rect = new Rect (0, 0, bitmap.getwidth (), Bitmap.getheight ());
RECTF RECTF = new RECTF (rect);
float roundpx = pixels;
Equivalent to clear screen
Canvas.drawargb (0, 0, 0, 0);
First drew a rectangle with rounded corners.
Canvas.drawroundrect (RECTF, ROUNDPX, ROUNDPX, paint);
Paint.setxfermode (New Porterduffxfermode (mode.src_in));
and draw the original bitmap to the present bitmap!!!. Pay attention to this understanding
Canvas.drawbitmap (Bitmap, rect, rect, paint);
return roundcornerbitmap;
}

}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.