Android image processing bitmap (2)

Source: Internet
Author: User

Bitmap related

1. Bitmap is more special because it can not be created and can only be aided by the bitmapfactory and according to the source of the image may be divided into the following situations:

* PNG images such as: R.drawable.tianjin

Java code
Bitmap bmp = Bitmapfactory.decoderesource (This.getresources (), R.drawable.tianjin); Load a resource picture

Bitmap bmp = Bitmapfactory.decoderesource (This.getresources (), R.drawable.tianjin);

* Image files such as:/sdcard/dcim/tianjin.jpeg

Java code
Bitmap bmp = Bitmapfactory.decodefile ("/sdcard/dcoim/tianjin.jpeg") load file picture
Bitmap bmp = Bitmapfactory.decodefile ("/sdcard/dcoim/tianjin.jpeg")

2. Bitmap Related applications

-Save Bitmap in sdcard with local save

* Create file for target files

Java code
File Fimage = new file ("/sdcard/dcim", "beijing.jpeg");

FileOutputStream IStream = new FileOutputStream (fimage);

File Fimage = new file ("/sdcard/dcim", "beijing.jpeg");

FileOutputStream IStream = new FileOutputStream (fimage);

* Remove Bitmap Oribmp

Java code
Oribmp.compress (Compressformat.jpeg, IStream); Save picture

Oribmp.compress (Compressformat.jpeg, IStream);


Refer to Bitmap's API method compress (bitmap.compressformat format, int quality, OutputStream stream)
Write a compressed version of the bitmap to the specified outputstream.
Written to the output stream, it is saved to the file.


Can be saved in several formats: Png,gif and other seemingly can, their own writing:
public void Savemybitmap (String bitname) throws IOException {
File F = new file ("/sdcard/note/" + Bitname + ". png");
F.createnewfile ();
FileOutputStream fOut = null;
try {
FOut = new FileOutputStream (f);
} catch (FileNotFoundException e) {
E.printstacktrace ();
}
Mbitmap.compress (Bitmap.CompressFormat.PNG, FOut);
try {
Fout.flush ();
} catch (IOException e) {
E.printstacktrace ();
}
try {
Fout.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}

-Get a picture of the Internet

* Define the Bufferedinputstream of the network picture

Java code
The link address of the picture
String Icouri = "Http://202.140.96.134:8080/FS-RSS/img/RN.png";

URL imgurl = new URL (IU);
URLConnection conn = Imgurl.openconnection ();

Conn.connect ();
InputStream is = Conn.getinputstream ();

Bufferedinputstream bis = new Bufferedinputstream (IS);

The link address of the picture
String Icouri = "Http://202.140.96.134:8080/FS-RSS/img/RN.png";

URL imgurl = new URL (IU);
URLConnection conn = Imgurl.openconnection ();

Conn.connect ();
InputStream is = Conn.getinputstream ();

Bufferedinputstream bis = new Bufferedinputstream (IS);

* Download the

Java code
Bitmap bmp = Bitmapfactory.decodestream (bis);

Bitmap bmp = Bitmapfactory.decodestream (bis);

* Close Stream

Java code
Bis.close ();

Is.close ();


Bitmaps are the most commonly used resource in our development, after all, a beautiful interface is the most attractive to the user.
1. Getting a bitmap from a resource

You can use bitmapdrawable or bitmapfactory to get a bitmap from a resource.

Of course, you need to get resources first:

Resources res=getresources ();

Get a bitmap using bitmapdrawable

1.
Use Bitmapdrawable (InputStream is) to construct a bitmapdrawable;
2.
Using the Bitmapdrawable class of Getbitmap () to obtain the bitmap;

Read the InputStream and get the bitmap
InputStream Is=res.openrawresource (r.drawable.pic180);
Bitmapdrawable bmpdraw=new bitmapdrawable (IS);
Bitmap Bmp=bmpdraw.getbitmap ();

Or use the following method:

Bitmapdrawable bmpdraw= (bitmapdrawable) res.getdrawable (r.drawable.pic180);
Bitmap Bmp=bmpdraw.getbitmap ();

Get a bitmap using Bitmapfactory

(creates Bitmap objects from various sources, including files, streams, and byte-arrays.)

Use the Bitmapfactory class Decodestream (InputStream is) to decode the bitmap resource and get the bitmap.

Bitmap Bmp=bitmapfactory.decoderesource (res, r.drawable.pic180);

All the functions of bitmapfactory are static, and this helper class can get bitmaps through resource IDs, paths, files, data streams, and so on.

The above method is free to choose when programming, in the Android SDK description can support the image format as follows: PNG (preferred), JPG (acceptable), GIF (discouraged), and BMP (Android SDK Support Media Format).
2. Get information about a bitmap

To get the bitmap information, such as bitmap size, pixels, density, transparency, color format, and so on, get the bitmap will be solved, this information in bitmap's manual, here is only auxiliary to explain the following 2 points:

*
Using the Bitmap.config definition for RGB color format in bitmap, only includes Alpha_8, argb_4444, argb_8888, rgb_565, missing some other, such as rgb_555, may need to pay attention to this small problem in the development;
*
Bitmap also provides a compress () interface to compress images, but Androidsak only supports PNG, JPG compression, and other formats that need to be supplemented by Android developers themselves.

3. Displaying bitmaps

Display bitmaps can use the core class canvas, display bitmaps through the canvas class's Drawbirmap (), or draw bitmap to canvas with the help of bitmapdrawable. Of course, the bitmap can also be displayed in the view by Bitmapdrawable.

Convert to Bitmapdrawable object display bitmap

Get bitmap
Bitmap Bmp=bitmapfactory.decoderesource (res, r.drawable.pic180);
Convert to Bitmapdrawable Object
Bitmapdrawable bmpdraw=new bitmapdrawable (BMP);
Show bitmap
ImageView iv2 = (ImageView) Findviewbyid (R.ID.IMAGEVIEW02);
Iv2.setimagedrawable (Bmpdraw);

displaying bitmaps using the canvas class

Here is a subclass panel that inherits from view, which is displayed in the OnDraw of the subclass

public class Mainactivity extends Activity {
/** called when the activity is first created. */
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (New Panel (this));
}

Class Panel extends view{
Public Panel (Context context) {
Super (context);
}
public void OnDraw (canvas canvas) {
Bitmap bmp = Bitmapfactory.decoderesource (Getresources (), r.drawable.pic180);
Canvas.drawcolor (Color.Black);
Canvas.drawbitmap (BMP, Ten, ten, null);
}
}
}

4. Bitmap Scaling

(1) Re-draw a bitmap as required, the bitmap is what we need, and the bitmap display almost the same: Drawbitmap (Bitmap Bitmap, rect src, rect dst, paint paint).

(2) on the basis of the original bitmap, scale the in-place map to create a new bitmap: CreateBitmap (Bitmap source, int x, int y, int width, int height, Matrix m, Boolean filter)

(3) with the help of the canvas scale (float SX, float sy) (Preconcat the present matrix with the specified scales), but be aware that the entire canvas is scaled at this time.

(4) with matrix:

Bitmap bmp = Bitmapfactory.decoderesource (Getresources (), r.drawable.pic180);
Matrix matrix=new Matrix ();
Matrix.postscale (0.2f, 0.2f);
Bitmap Dstbmp=bitmap.createbitmap (Bmp,0,0,bmp.getwidth (),
Bmp.getheight (), matrix,true);
Canvas.drawcolor (Color.Black);
Canvas.drawbitmap (Dstbmp, ten, ten, null);

5. Bitmap rotation

Similarly, the rotation of the bitmap can be achieved with the help of matrix or canvas.

Bitmap bmp = Bitmapfactory.decoderesource (Getresources (), r.drawable.pic180);
Matrix matrix=new Matrix ();
Matrix.postscale (0.8f, 0.8f);//Zoom
Matrix.postrotate (45);//rotation
Bitmap Dstbmp=bitmap.createbitmap (Bmp,0,0,bmp.getwidth (),
Bmp.getheight (), matrix,true);
Canvas.drawcolor (Color.Black);
Canvas.drawbitmap (Dstbmp, ten, ten, null);

Rotation effect:

Image

Image


6. How to generate image watermark

The process of generating a watermark. In fact, there are three links: first, load the original picture; second, load the watermark picture; third, save the new picture.

* /**
* * Create the bitmap from a byte array
*     *
* * @param src the Bitmap object you want Proecss
* * @param watermark The water mark above the SRC
* * @return return a Bitmap object, if paramter ' s length is 0,return null
*     */
* Private Bitmap CreateBitmap (Bitmap src, Bitmap watermark)
*    {
* String tag = "CreateBitmap";
* LOG.D (Tag, "Create a new bitmap");
* if (src = = null)
*        {
* return null;
*        }
*
* Int w = src.getwidth ();
* int h = src.getheight ();
* int ww = watermark.getwidth ();
* INT wh = watermark.getheight ();
*//create the new blank bitmap
* Bitmap newb = Bitmap.createbitmap (W, H, config.argb_8888);//Create a new bitmap with the same src length width
* Canvas CV = new canvas (NEWB);
*//draw src into
* CV.DRAWBITMAP (SRC, 0, 0, NULL);//at 0, 0 coordinates begin to draw into SRC
*//draw Watermark into
* CV.DRAWBITMAP (watermark, W-WW + 5, H-WH + 5, NULL);//Draw a watermark in the lower right corner of SRC
*//save All Clip
* Cv.save (Canvas.all_save_flag);//Save
*//store
* Cv.restore ();//Storage
* Return newb;
*    }


7.Canvas of Save and restore

The OnDraw method passes in a canvas object, which is the one you use to draw the visual interface of the control.

In the OnDraw method, we often see calls to the Save and restore methods, what exactly are they used for?

? Save: Used to save the state of the canvas. After save, you can invoke canvas panning, indenting, rotating, trimming, cropping, and so on.

? Restore: The state used to restore the canvas before it is saved. Preventing the actions that are performed on the canvas after save has an impact on subsequent drawing.

Save and restore are paired (restore can be less than save, but not many), and error will be raised if the restore is called more times than save. Between save and restore, there is often a special manipulation of the canvas.

For example: We would like to draw a right-pointing triangular arrow on the canvas, of course, we can draw directly, in addition, we can also rotate the canvas 90 °, draw an upward arrow, and then rotate back (this rotation is very useful for the marker on the circumference of the drawing). Then, we want to have a 20-pixel circle in the lower-right corner, so the core code in OnDraw is:

int px = Getmeasuredwidth ();

int py = Getmeasuredwidth ();

Draw background

Canvas.drawrect (0, 0, px, py, backgroundpaint);

Canvas.save ();

Canvas.rotate (PX/2, PY/2);

Draw Up ARROW

Canvas.drawline (PX/2, 0, 0, PY/2, linepaint);

Canvas.drawline (PX/2, 0, px, PY/2, linepaint);

Canvas.drawline (PX/2, 0, PX/2, py, linepaint);

Canvas.restore ();

Draw Circle

Canvas.drawcircle (px-10, py-10, ten, linepaint);

The effect 1 shows:

What would it look like if we didn't call save and restore? 2 is shown below:

From these two graphs, we can see the obvious difference in the position of the circle. Without the save and restore operations of the canvas, all images are drawn on the canvas after the canvas rotates 90°. When the OnDraw method is executed, the system automatically restores the canvas back. When the save and restore operations are executed differently, they can cause the drawing to be different.

Android image processing bitmap (2)

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.