العمل مع الصور في PHP: مكتبات GD و Imagick
معالجة الصور هي إحدى المهام الأساسية في تطوير الويب. في PHP، تُستخدم مكتبتان رئيسيتان لهذا الغرض: GD (مضمنة) و Imagick (غلاف لـ ImageMagick). في هذه المقالة، سنستعرض إمكانياتهما، ونتعلم كيفية تغيير الأحجام، والقص، وإضافة العلامات المائية، وتحسين الصور.
1. مكتبة GD
GD هي إضافة PHP قياسية، متوفرة في معظم خدمات الاستضافة. تتيح لك إنشاء الصور وتعديلها وحفظها بتنسيقات JPEG و PNG و GIF و WebP.
التفعيل والتحقق:
<?php// التحقق من تثبيت إضافة GDif (extension_loaded('gd') && function_exists('gd_info')) { echo "GD مثبتة: "; print_r(gd_info());} else { echo "لم يتم العثور على GD";}?>1.1 تغيير حجم الصورة (resize)
السيناريو الأكثر شيوعًا هو تصغير الصورة إلى الأبعاد المطلوبة مع الحفاظ على النسب.
<?phpfunction resizeImage($sourcePath, $destPath, $newWidth, $newHeight) { // الحصول على أبعاد الصورة الأصلية list($width, $height, $type) = getimagesize($sourcePath); // إنشاء مورد من الملف الأصلي switch ($type) { case IMAGETYPE_JPEG: $source = imagecreatefromjpeg($sourcePath); break; case IMAGETYPE_PNG: $source = imagecreatefrompng($sourcePath); break; case IMAGETYPE_GIF: $source = imagecreatefromgif($sourcePath); break; default: return false; } // إنشاء صورة جديدة $newImage = imagecreatetruecolor($newWidth, $newHeight); // الحفاظ على الشفافية لـ PNG/GIF imagealphablending($newImage, false); imagesavealpha($newImage, true); // النسخ وإعادة التحجيم imagecopyresampled($newImage, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); // حفظ النتيجة imagejpeg($newImage, $destPath, 85); // جودة 85% // تحرير الذاكرة imagedestroy($source); imagedestroy($newImage); return true;}
// مثال على الاستخدامresizeImage('photo.jpg', 'photo_thumb.jpg', 300, 200);?>1.2 قص الصورة (crop)
يتيح القص استخراج الجزء المركزي من الصورة بالأبعاد المطلوبة.
<?phpfunction cropCenter($sourcePath, $destPath, $cropWidth, $cropHeight) { list($width, $height) = getimagesize($sourcePath); $source = imagecreatefromjpeg($sourcePath); // حساب إحداثيات المركز $x = ($width - $cropWidth) / 2; $y = ($height - $cropHeight) / 2; $newImage = imagecreatetruecolor($cropWidth, $cropHeight); imagecopyresampled($newImage, $source, 0, 0, $x, $y, $cropWidth, $cropHeight, $cropWidth, $cropHeight); imagejpeg($newImage, $destPath, 90); imagedestroy($source); imagedestroy($newImage);}
cropCenter('photo.jpg', 'photo_cropped.jpg', 400, 400);?>1.3 إضافة علامة مائية
إضافة نص أو شعار فوق الصورة.
<?phpfunction addWatermarkText($sourcePath, $destPath, $text = "© PythonLib.ru") { $source = imagecreatefromjpeg($sourcePath); $width = imagesx($source); $height = imagesy($source); // لون النص (أبيض مع شفافية) $color = imagecolorallocatealpha($source, 255, 255, 255, 50); // حجم الخط (استخدام الخط المدمج) $fontSize = 5; $x = 10; $y = $height - 20; imagestring($source, $fontSize, $x, $y, $text, $color); imagejpeg($source, $destPath, 90); imagedestroy($source);}
addWatermarkText('photo.jpg', 'photo_watermarked.jpg');?>