PHP操作Imagick庫可以實現不少圖片效果,比如在一張圖片上,打印8*10的數字矩陣。以上效果的實現方法如下:
PHP操作Imagick庫代碼
- //格子的尺寸
- $grid_font_size = 18; //字體大小
- $grid_font_color = "#000"; //字體顏色
- $grid_width = 36; //格子的寬度
- $grid_height = 24; //格子的高度
- $grid_origin_x = 15; //左上角的數字的起始橫坐標
- $grid_origin_y = 98; //左上角的數字的起始縱坐標
- #原圖
- $image = new Imagick('background.jpg');
- #寫入密保卡數據
- $tmp_grid_origin_x = $grid_origin_x;
- $tmp_grid_origin_y = $grid_origin_y;
- foreach ($pData as $k => $v){
- foreach ($v as $k_grid_data => $v_grid_data){
- $tmp_grid_origin_x += $grid_width;
- $draw = new ImagickDraw();
- $draw->setFillColor($grid_font_color);
- $draw->setFontSize($grid_font_size);
- $draw->annotation($tmp_grid_origin_x, $tmp_grid_origin_y, $v_grid_data);
- $image->drawImage($draw);
- }
- $tmp_grid_origin_x = $grid_origin_x;
- $tmp_grid_origin_y += $grid_height;
- }
- $image->writeImage($ks_ImageSrcPath. $pSN. '.jpg');
- #釋放資源
- $image->destroy();
- $draw->destroy();
這樣做的後果是,在每次循環的時候,都要實例化一個ImagickDraw,並執行drawImage方法,非常占用CPU資源。
可以從以下兩點優化:
1. 不必每次都執行new操作,一個就夠了;
2. 不必每次都執行drawImage方法,一次就夠了。也就是說,annotation方法好像具有“附加”的意味,不用擔心後來的覆蓋掉之前的;
PHP操作Imagick庫優化後代碼如下:
- $draw = new ImagickDraw();
- $draw->setFillColor($grid_font_color);
- $draw->setFontSize($grid_font_size);
- foreach ($pData as $k => $v){
- foreach ($v as $k_grid_data => $v_grid_data){
- $tmp_grid_origin_x += $grid_width;
- $draw->annotation($tmp_grid_origin_x, $tmp_grid_origin_y, $v_grid_data);
- }
- $tmp_grid_origin_x = $grid_origin_x;
- $tmp_grid_origin_y += $grid_height;
- }
- $image->drawImage($draw);