Detailed Android development MP4 file gif file _android

Source: Internet
Author: User
Tags image identifier transparent color


A basic principle of realization



In the introduction of the specific implementation process, the first simple to say the basic principles and implementation steps, in the solution of relatively complex problems, I am accustomed to first clear the main principle of the steps, do not start by the cumbersome details of the trip, waiting for the specific implementation and then one by one. The following are the main steps:



1, video file reading: including recording and local file reading



2, the need to convert the video part of the resolution to Bitmap sequence



3, will parse the good Bitmap sequence code to generate the GIF file



Reading of two video files



Video file reading is relatively simple, there is no special need to say where, here simply paste the core of the video reading code, detailed implementation can be Google for a while on the line.


Private View.onclicklistener Clicklistener = new View.onclicklistener () {
 @Override public
 void OnClick (View v) {
 Intent Intent = new Intent ();
 Intent.settype ("video/*");
 Intent.setaction (intent.action_get_content);
 Startactivityforresult (Intent.createchooser (Intent, "select Video"), Select_video);
 
@Override
protected void onactivityresult (int requestcode, int resultcode, Intent data) {
 if (Requestcode = RE Quest_select_video) {
 if (ResultCode = = RESULT_OK) {
  Uri Videouri = Data.getdata ();
  FilePath = Getrealfilepath (Videouri);
 }}}


The analysis of three video files



After the successful reading of the video file, the next thing to do is to parse the video file, select the video clips that need to be converted, and extract the bitmap sequence. The following specific implementation, extraction BITMAP sequence is based on the given start time and end time and frame rate from the video file to obtain the corresponding Bitmap, this article is mainlyMediaMetadataRetrieverto use the API provided to achieve, before looking at the code can look atMediaMetadataRetrieverthe API document, The core function of this class is to get the frame and metadata of the video, the following is the core implementation code:


Public list<bitmap> createbitmaps (String path) {
 mediametadataretriever MMR = new Mediametadataretriever (); C2/>mmr.setdatasource (path);
 Double inc = 1000 * 1000/FPS;
 
 for (double i = begin; I < i + + Inc) {
 Bitmap frame = mmr.getframeattime (long) I, Mediametadataretriever.opti On_closest);
 if (frame!= null) {
  Bitmaps.add (scale (frame));
 }
 
 return bitmaps;
}
 
Private Bitmap Scale (Bitmap Bitmap) {return
 Bitmap.createscaledbitmap (Bitmap,
 width > 0? width:bitmap.ge Twidth (),
 height > 0 height:bitmap.getHeight (),
 true);


Four Generate GIF files



To get the Bitmap sequence to generate the GIF, the next thing you need to do is encode the data in the Bitmap sequence into the GIF file format and generate the final GIF file. The goal is very clear, then see the specific implementation process.



1. GIF Format Introduction



Create GIF file before it is necessary to introduce the storage format of GIF, GIF format related articles are more, there is no need for too detailed introduction, but simply say later in the program will be used in the aspect.



A GIF image is based on a color list (the stored data is the index value of the point that corresponds to the color list) and supports up to 8 bits (256 colors). GIF files are divided into a number of storage blocks, used to store multiple images or to determine the behavior of the image of the control block for animation and interactive applications. GIF files also compress image data by compressing the LZW algorithm to reduce the image size.



GIF files are divided into blocks, including control blocks and data blocks. The control block acts as a block of data, depending on the control block contains a number of different control parameters; The data block contains only a few 8-bit character streams, and its function is determined by the control blocks in front of it, each data block 0 to 255 bytes, the first byte of the data block indicates the block size (bytes), This byte is not included when calculating the size of a block of data, so an empty block of data has a byte, which is the size of the block of data 0x00.



2. GIF File Write



The beginning of contact with GIF files will feel more complex, storage format, coding format, etc. than Bitmap more complex, but in fact, can simplify the understanding of the problem, generated GIF and generate Bitmap similar principle, that is, in accordance with the format of the prescribed file on the line, not too tangled inside the details, Otherwise you will get into tedious details (commonly known as dead ends) and ignore the ultimate goal just to generate GIF files. Here's a look at some of the files that need to be written:



Extract the pixel value of the Bitmap



First we need to extract the pixel values of the Bitmap above, convenient to write the pixel value to the GIF file, in the extraction of pixel values, the production of GIF files required by the color table, the process of producing color table is more complex, here is not to post the source code, interested in Google color quantization algorithm, Not interested directly with ready-made is good, the following is the realization of pixel values:


protected void Getimagepixels () {
 int w = image.getwidth ();
 int h = image.getheight ();
 pixels = new Byte[w*h*3];
 for (int i = 0; i < H; i++) {
 int stride = w * 3 * i;
 for (int j = 0; J < W J + +) {
  int p = image.getpixel (J, i);
  int step = J * 3;
  int offset = stride + step;
  Blue
  pixels[offset+0] = (byte) (P & 0x0000ff) >> 0);
  Green
  pixels[offset+1] = (byte) (P & 0x00ff00) >> 8);
  Red
  pixels[offset+2] = (byte) ((P & 0xff0000) >>);} 
 }


GIF file Header (header)



The header portion of the file is a total of 6 bytes, includes GIF signature and version number, GIF signature consists of 3 characters "GIF", a total of 3 bytes, the version number is also composed of 3 bytes, can be "87a" or "89a" (respectively for the 1987 and 1989 versions), the implementation code is as follows:


Write file header
protected void Writeheader () throws IOException {
 writestring ("gif89a");
}
 
protected void WriteString (String s) throws IOException {for
 (int i = 0; i < s.length (); i++) {
 out.write (byt e) S.charat (i));
 }


Logical screen Identifier (Logical screens descriptor)



The file header is followed by a logical screen identifier (Logical screens descriptor), which is composed of 7 bytes, defining the size of the GIF image, its color depth, the background color, and the number of indexes with no global color list and color list. The implementation code is as follows:


Write logical screen identifier
protected void Writelsd () throws IOException {
 writeshort (width);//write Image width
 writeshort ( height);  Write Image Height
 
 out.write (0x80 |//Global Color list flag set 1
    0x70 |//Determine Image Color depth (7+1=8)
    0x00 |//Global Color list sorted to 0
    0x07)); The index number of the color list (2 7+1)
 
 out.write (0);///Background color (index in global Color list)
 out.write (0);//pixel width ratio default 1:1
}
 
protected void Writeshort (int value) throws IOException {
 out.write (value & 0xff);
 Out.write ((Value >> 8) & 0xff);
}


The logical screen identifier part of the structure is slightly more complicated, and if you don't know what each one means, you can refer to the Logical Screen Identifier section in the GIF graphics file format document.



Global Color list (globally color Table)



The global color list must be immediately following the logical screen identifier, each color list index entry is composed of three bytes, in the order of R, G, B, the realization of the specific generation of color table can see the Source code section, due to the complex production process, here is not to paste the color table generated codes, the following is written to the color table code:


Write color table
protected void Writepalette () throws IOException {
 out.write (colortab, 0, colortab.length);
 int n = (3 * 256)-colortab.length;
 for (int i = 0; i < n; i++) {
 out.write (0);
 }
}


Graphics control Extensions (Graphic controls Extension)



This part is optional, the 89a version is supported and can be placed in front of an image block (including an image identifier, a local color list and image data) or a text extension block to control the rendering (Render) Form of the first image (or text) that follows it, following the implementation code:


protected void Writegraphicctrlext () throws IOException {
 out.write (0x21);//extension block identification, fixed value 0x21
 out.write (0XF9); /graphics Control extended label, fixed value 0xf9
 out.write (4);//block size, fixed value 4
 out.write (0 |//1:3 reserved bit
   0 |//4:6 do not use disposal method
   0 |//7 user input Flag 0
   0); 8 Transparent Color Mark 0
 
 writeshort (delay);//Delay Time
 out.write (0);  Transparent Color index value
 out.write (0);  Block terminator, fixed value 0
}


Image identifier (image descriptor)



A GIF file can contain several images, after the end of an image is an image identifier, the image identifier begins with the 0x2c (', ') character, defining the character of its image, including the offset of the image relative to the logical screen boundary, The image size and the size of the local color list and color list, consisting of 10 bytes, follow the implementation code:


protected void Writeimagedesc () throws IOException {
 out.write (0x2c);//Image identifier begins with a fixed value of 0x2c
 writeshort (0);  X Direction offset
 writeshort (0);  Y-Direction offset writeshort (width
 );//Image width
 writeshort (height);//Image Height
 out.write (
  0x80 |  Local color list flag 1
  0x00 |
  0x00 |
  0x07));  Index number of local color list (7+1 of 2)
}


Image (image data)



GIF image data using the LZW compression algorithm, greatly reducing the size of the image data, the specific LZW compression algorithm can be Google, the program implementation section can refer to the source link at the bottom of the article. The following is a write implementation of the image data:


protected void WritePixels () throws IOException {
 Lzwencoder encoder = new Lzwencoder (
  width, height, Indexedpixe LS, colordepth);
 Encoder.encode (out);
}


File Terminator (Trailer)



This part has only one byte, identifies the end of a GIF file, the fixed value is 0x3b, implements the code:


public void Finish () throws IOException {
 out.write (0x3b);
 Out.flush ();
 Out.close ();
}


Summarize



So far, the process of converting MP4 files to GIF files is basically complete, if you need to cut GIF files, add watermarks, and so on, you can write gif in the Bitmap sequence before the Bitmap for the corresponding processing can be, if there are any problems welcome to Exchange learning. I hope the content of this article for everyone's learning work can help.


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.