PHP image cropping server setup
在我们的工作的项目中,有时候我们需要显示规定尺寸的图片,虽然可以通过css来控制显示大小。但是如果图片过大,会造成加载的延迟,影响网站整体性能。因此,我们需要一个服务器来帮助我们进行图片的裁剪。流程大致是,首先我们传给服务器原图像和裁剪的尺寸,然后服务器进行裁剪,生成对应的裁剪图片,下次我们再访问相同图像和相同的裁剪尺寸的时候,我们就不需要裁剪,直接进行图片的访问就行。
Talk is cheap, show me the code.
<?php // ①构建图片请求地址比如 http://xxx.com/resize.php?site=www&width=300&height=200&mode=2&path=uploadfile/helloworld.png // ②配置nginx重写规则 rewrite /s/(.*)/(\d+)x(\d+)-(\d)/(.*) /s/resize.php?site=$1&width=$2&height=$3&mode=$4&path=$5 last; //③进行裁剪图片的处理 $path = trim($_GET['path']); $mode = intval($_GET['mode']); $site = trim($_GET['site']); $width = intval($_GET['width']); $height = intval($_GET['height']); $site_list = array('crop' => '.'); $orig_dir = dirname(__FILE__); if (!array_key_exists($site, $site_list)) { header('HTTP/1.1 400 Bad Request'); exit(); } if ($mode > 3 || $mode < 0) { header('HTTP/1.1 400 Bad Request'); exit(); } $orig_file = $site_list[$site] . $path; if (!file_exists($orig_file)) { header('HTTP/1.1 404 Not Found'); exit(); } $file_ext = '.' . pathinfo($path, PATHINFO_EXTENSION); $file_name = basename($path, $file_ext); $save_path = "{$orig_dir}/{$site}/{$width}x{$height}-{$mode}{$path}"; $save_dir = dirname($save_path); if (!file_exists($save_dir)) { wpx_mkdir($save_dir); } $target_width = $width; $target_height = $height; $save_image = $save_dir . '/' . $file_name . '.jpg'; if (file_exists($save_image)) { header('Content-Type: image/jpeg'); header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); echo file_get_contents($save_image); } imagecropper2($orig_file, $target_width, $target_height, $save_image); die; //原图像对应缩放裁剪,会拉伸图片 function imagecropper2($source_path, $width, $height, $save_image) { //获取原图像$filename的宽度$width_orig和高度$height_orig $info = getimagesize($source_path); $width_orig = $info[0]; $height_orig = $info[1]; $mime = $info['mime']; //根据参数$width和$height值,换算出等比例缩放的高度和宽度 if ($width && ($width_orig<$height_orig)){ $width = ($height/$height_orig)*$width_orig; }else{ $height = ($width / $width_orig)*$height_orig; } //将原图缩放到这个新创建的图片资源中 $image_p = imagecreatetruecolor($width, $height); //获取原图的图像资源 if($mime=='image/jpeg'){ $image = imagecreatefromjpeg($source_path); }elseif($mime=='image/png'){ $image = imagecreatefrompng($source_path); }elseif($mime=='image/gif'){ $image = imagecreatefromgif($source_path); } //使用imagecopyresampled()函数进行缩放设置 imagecopyresampled($image_p,$image,0,0,0,0,$width,$height,$width_orig,$height_orig); //将缩放后的图片$image_p保存,100(质量最佳,文件最大) if($mime=='image/jpeg'){ imagejpeg($image_p,$save_image); header('Content-Type: image/jpeg'); imagejpeg($image_p); }elseif($mime=='image/png'){ imagepng($image_p,$save_image); header('Content-Type: image/jpeg'); imagepng($image_p); }else{ imagegif($image_p,$save_image); header('Content-Type: image/jpeg'); imagegif($image_p); } } //进行比例保存裁剪,会丢失图像部分像素 function imagecropper($source_path, $target_width, $target_height, $save_image) { $source_info = getimagesize($source_path); $source_width = $source_info[0]; $source_height = $source_info[1]; $source_mime = $source_info['mime']; $source_ratio = $source_height / $source_width; $target_ratio = $target_height / $target_width; // 源图过高 if ($source_ratio > $target_ratio) { $cropped_width = $source_width; $cropped_height = $source_width * $target_ratio; $source_x = 0; $source_y = ($source_height – $cropped_height) / 2; } // 源图过宽 elseif ($source_ratio < $target_ratio) { $cropped_width = $source_height / $target_ratio; $cropped_height = $source_height; $source_x = ($source_width – $cropped_width) / 2; $source_y = 0; } // 源图适中 else { $cropped_width = $source_width; $cropped_height = $source_height; $source_x = 0; $source_y = 0; } switch ($source_mime) { case 'image/gif': $source_image = imagecreatefromgif($source_path); break; case 'image/jpeg': $source_image = imagecreatefromjpeg($source_path); break; case 'image/png': $source_image = imagecreatefrompng($source_path); break; default: return false; break; } $target_image = imagecreatetruecolor($target_width, $target_height); $cropped_image = imagecreatetruecolor($cropped_width, $cropped_height); // 裁剪 $bool = imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height); // 缩放 $bool = imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height); imagejpeg($target_image, $save_image); header('Content-Type: image/jpeg'); imagejpeg($target_image); imagedestroy($source_image); imagedestroy($target_image); imagedestroy($cropped_image); } // 循环生成目录 function wpx_mkdir($dir, $mode = 0777) { if (is_dir($dir) || @mkdir($dir, $mode)) { return true; } if (!wpx_mkdir(dirname($dir), $mode)) { return false; } return @mkdir($dir, $mode); }
通过上面的处理,我们就将图片按照我们设置的尺寸进行了裁剪。我们还可以定期对裁剪图片进行清理,这样就不需要占用太多服务器空间。只有经常访问的图片才会一直保存。
更多PHP相关知识,请访问PHP中文网!
The above is the detailed content of PHP image cropping server setup. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

<p>Windows 11 improves personalization in the system, allowing users to view a recent history of previously made desktop background changes. When you enter the personalization section in the Windows System Settings application, you can see various options, changing the background wallpaper is one of them. But now you can see the latest history of background wallpapers set on your system. If you don't like seeing this and want to clear or delete this recent history, continue reading this article, which will help you learn more about how to do it using Registry Editor. </p><h2>How to use registry editing

Inline frames are called iframes in HTML. A label specifies a rectangular area within the content where the browser can display different documents with scroll bars and borders. To embed another document within the current HTML document, use inline frames. A reference to an element can be specified using the HTMLiframe name attribute. In JavaScript, references to elements are also made using the name attribute. An iframe is essentially used to display a web page within the currently displayed web page. The URL of the document containing the iframe is specified using the "src" attribute. Syntax The following is the syntax of HTML <iframesrc="URL"title="d

Windows are never one to neglect aesthetics. From the bucolic green fields of XP to the blue swirling design of Windows 11, default desktop wallpapers have been a source of user delight for years. With Windows Spotlight, you now have direct access to beautiful, awe-inspiring images for your lock screen and desktop wallpaper every day. Unfortunately, these images don't hang out. If you have fallen in love with one of the Windows spotlight images, then you will want to know how to download them so that you can keep them as your background for a while. Here's everything you need to know. What is WindowsSpotlight? Window Spotlight is an automatic wallpaper updater available from Personalization > in the Settings app

Some users find that some things in the picture are crooked and cannot be directly selected and cropped. Is there any way to straighten the things in the picture? In fact, this operation is very simple for PS masters. Here, the editor will tell the novice PS users how to crop crooked pictures into straight ones in Photoshop. This method is very easy to operate. I hope it can help everyone. PS tutorial for cropping tilted photos 1. Open Photoshop, move the mouse to the cropping tool on the left, then right-click the mouse and select "Perspective Cropping Tool". 2. Select the picture that needs to be straightened and determine the four points. 3. Then press the Enter key to straighten it successfully. 4. In this way, the things in the photo will be corrected, and

With the continuous development of artificial intelligence technology, image semantic segmentation technology has become a popular research direction in the field of image analysis. In image semantic segmentation, we segment different areas in an image and classify each area to achieve a comprehensive understanding of the image. Python is a well-known programming language. Its powerful data analysis and data visualization capabilities make it the first choice in the field of artificial intelligence technology research. This article will introduce how to use image semantic segmentation technology in Python. 1. Prerequisite knowledge is deepening

Those who have to work with image files on a daily basis often have to resize them to fit the needs of their projects and jobs. However, if you have too many images to process, resizing them individually can consume a lot of time and effort. In this case, a tool like PowerToys can come in handy to, among other things, batch resize image files using its image resizer utility. Here's how to set up your Image Resizer settings and start batch resizing images with PowerToys. How to Batch Resize Images with PowerToys PowerToys is an all-in-one program with a variety of utilities and features to help you speed up your daily tasks. One of its utilities is images

With the iOS 17 Photos app, Apple makes it easier to crop photos to your specifications. Read on to learn how. Previously in iOS 16, cropping an image in the Photos app involved several steps: Tap the editing interface, select the crop tool, and then adjust the crop using a pinch-to-zoom gesture or dragging the corners of the crop tool. In iOS 17, Apple has thankfully simplified this process so that when you zoom in on any selected photo in your Photos library, a new Crop button automatically appears in the upper right corner of the screen. Clicking on it will bring up the full cropping interface with the zoom level of your choice, so you can crop to the part of the image you like, rotate the image, invert the image, or apply screen ratio, or use markers

Thanks to the differentiable rendering provided by NeRF, recent 3D generative models have achieved stunning results on stationary objects. However, in a more complex and deformable category such as the human body, 3D generation still poses great challenges. This paper proposes an efficient combined NeRF representation of the human body, enabling high-resolution (512x256) 3D human body generation without the use of super-resolution models. EVA3D has significantly surpassed existing solutions on four large-scale human body data sets, and the code has been open source. Paper name: EVA3D: Compositional 3D Human Generation from 2D image Collections Paper address: http
