1. 程式人生 > >libpng處理png圖片(二)

libpng處理png圖片(二)

剪切圖片 run pen != bsp col pla lap malloc

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

        技術分享

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

       技術分享

           切割後的小圖片

  拼圖的效果與此類似.

二,實現思想

  利用上一篇所展示的libpng讀寫圖片的函數,讀出圖片的數據域,然後對數據域進行"剪切"或者拼接獲得新圖片的數據域,最後通過libpng的庫函數寫入圖片即可.

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

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

  難點:由於代碼中圖片數據域的表示方法為一維數組,導致獲取指定行和列的某個像素時需要對一維數組做處理當做二維的來使用

  代碼:

技術分享
 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

libpng處理png圖片(二)