libpng處理png圖片(二)

一,實現效果:圖片剪切, 圖片拼接數組

           

                -------切割後----->ide

           

                               切割後的小圖片函數

 

  拼圖的效果與此相似.spa

 

二,實現思想code

  利用上一篇所展現的libpng讀寫圖片的函數,讀出圖片的數據域,而後對數據域進行"剪切"或者拼接得到新圖片的數據域,最後經過libpng的庫函數寫入圖片便可.blog

 

三,剪切圖片的核心代碼(代碼內含註釋)圖片

  思路:讀出一張大圖片的數據域buff, 按照數據與圖片中像素對應的原則, 依次獲取切割後每一個小圖片的數據域png_buff(像素矩陣)string

  難點:因爲代碼中圖片數據域的表示方法爲一維數組,致使獲取指定行和列的某個像素時須要對一維數組作處理當作二維的來使用it

  代碼:event

 1 void PngOper::run()
 2 {
 3     cout << "你好" << endl;
 4     char * filePath = "C:\\Users\\Administrator\\Desktop\\切圖 - 副本\\map_1001.png";
 5     int width = 0;
 6     int height = 0;
 7     
 8     readPngInfo(filePath, &width, &height);
 9     cout << "讀取信息:" << width << "*" << height << endl;
10 
11     
12     //小塊兒圖片的寬,高
13     int cfg_width = 192;
14     int cfg_height = 180;
15 
16     //計算分割的小圖片的行,列數目
17     int gW = width / cfg_width;
18     int exceedWidth = width % cfg_width;
19     int gH = height / cfg_height;
20     int exceedHeight = height % cfg_height;
21 
22     int h = exceedHeight > 0 ? (gH + 1) : gH;
23     int w = exceedWidth > 0 ? (gW + 1) : gW;
24 
25     //讀取大圖片數據域
26     RGBA_data *buff = (RGBA_data *)malloc(width*height*sizeof(RGBA_data));
27     load_png_image(filePath, &width, &height, buff);
28 
29     //分配小塊兒地圖的數據域
30     RGBA_data *png_buff = (RGBA_data *)malloc(cfg_width * cfg_height * sizeof(RGBA_data));
31     for (int i = 0; i < h; i++)
32     {
33         for (int j = 0; j < w; j++)
34         {
35             //1.獲取png_buff數據域
36             buffCopy(buff, width, height, png_buff, cfg_width, cfg_height, j*cfg_width, i*cfg_height);
37             //2.寫圖片
38             int idx = i*w + j + 1;
39             string fileName = "C:\\Users\\Administrator\\Desktop\\切圖 - 副本\\" + to_string(idx) + ".png";
40             write_RGBA_Image(fileName.c_str(), cfg_width, cfg_height, "test", png_buff);
41         }
42     }
43 
44     if (buff != nullptr)
45     {
46         free(buff);
47         buff = nullptr;
48     }
49     if (png_buff != nullptr)
50     {
51         free(png_buff);
52         png_buff = nullptr;
53     }
54 }
View Code

 

四,注意

  png圖片的color_type有多種,包括熟知的RGB類型與RGBA類型,經過讀取圖片信息能夠獲取該內容.

  進行圖片讀寫時要兼顧多種類型的color_type

相關文章
相關標籤/搜索