imagemagick使用_使用ImageMagick裁剪和调整图像大小

imagemagick使用

If your website allows users to upload photos, image cropping/resizing functionality certainly comes in handy. But users might not have access to image manipulation tools like Photoshop, so by providing a cropping/resizing feature you can allow users to upload photos from any device (e.g. tablets or phones) without them having to worry about the the final size. Furthermore, you can create different versions of the same image and also allow users to crop specific portions of uploaded picture.

如果您的网站允许用户上传照片,则图像裁剪/调整大小功能肯定会派上用场。 但是用户可能无法使用Photoshop等图像处理工具,因此,通过提供裁剪/调整大小功能,您可以允许用户从任何设备(例如平板电脑或手机)上载照片,而不必担心最终尺寸。 此外,您可以创建同一图像的不同版本,并且还允许用户裁剪上载图片的特定部分。

In this article I’ll show you how to create an image cropping tool with the help of the ImageMagick PHP extension. This tutorial assumes that you already have the extension installed, so if not then be sure to read the manual.

在本文中,我将向您展示如何在ImageMagick PHP扩展的帮助下创建图像裁剪工具。 本教程假定您已经安装了扩展程序,因此如果没有安装扩展程序,请务必阅读手册

熟悉 (Getting Familiar)

The ImageMagick extension performs image processing using the ImageMagick library. ImageMagick provides a lot of API methods through which you can manipulate an image. It offers a simple object-oriented interface to use the API; you just need to create an instance of the Imagick class and then call the appropriate methods to start manipulating the images.

ImageMagick扩展使用ImageMagick库执行图像处理。 ImageMagick提供了许多API方法,您可以通过它们来处理图像。 它提供了一个简单的面向对象的接口来使用API​​。 您只需要创建Imagick类的实例,然后调用适当的方法即可开始处理图像。

Since we’re going to create an image cropper, we’ll mostly be using the two methods: cropImage() and thumbnailimage().

由于我们将要创建图像裁剪器,因此我们将主要使用两种方法: cropImage()thumbnailimage()

cropImage (cropImage)

The cropImage() method accepts four arguments. The first two arguments indicate the height and width of the cropped region, and the last two indicate the X and Y coordinates of the top-left corner of the cropped area.

cropImage()方法接受四个参数。 前两个自变量指示裁剪区域的高度和宽度,后两个自变量指示裁剪区域左上角的X和Y坐标。

For example:

例如:

<?php
$inFile = "test.jpg";
$outFile = "test-cropped.jpg";
$image = new Imagick($inFile);
$image->cropImage(400,400, 30,10);
$image->writeImage($outFile);

We create an Imagick object first, passing to its constructor the filename of our image. Then we call cropImage() with appropriate arguments. In this case the code will produce a cropped image of size 400×400px starting at 30px from the top and 10px in from the left of the original image. Finally, writeImage() saves the result back to disk for us.

我们首先创建一个Imagick对象,并将图像的文件名传递给其构造函数。 然后我们调用带有适当参数的cropImage() 。 在这种情况下,代码将生成尺寸为400×400px的裁剪图像,从原始图像的顶部开始30px,左侧开始10px。 最后, writeImage()将结果保存回磁盘。

thumbnailImage (thumbnailImage)

The thumbnailImage() method simply accepts the height and width of the resized image and can be used as follows:

thumbnailImage()方法仅接受调整大小后的图像的高度和宽度,可以按以下方式使用:

<?php
$inFile = "test.jpg";
$outFile = "test-thumbnail.jpg";
$image = new Imagick($inFile);
$image->thumbnailImage(200, 200);
$image->writeImage($outFile);

The above code produces a 200×200px version of image. If either the width or height argument to thumbnailImage() is set as 0, the aspect ratio is maintained.

上面的代码生成200×200px版本的图像。 如果thumbnailImage()的width或height参数设置为0,则将保持宽高比。

We can also pass a third argument known as bestfit; If this is set true, the image will be resized in such a way that the new dimensions can be contained within the height and width specified. For example, a call to thumbnailImage(400, 400, true) on a 1200×768px image will produce a 400×200px version. The new dimensions are less than or equal to the specified dimensions.

我们还可以通过第三个论点,即“ 最佳拟合” ; 如果将其设置为true,则将调整图像的大小,以使新尺寸可以包含在指定的高度和宽度之内。 例如,对1200×768px图像上的thumbnailImage(400, 400, true) 400,400 thumbnailImage(400, 400, true)的调用将产生400×200px版本。 新尺寸小于或等于指定尺寸。

Now that you’re familiar with the two methods, we’re good to go.

既然您已经熟悉了这两种方法,那么我们就可以开始了。

上传和裁剪 (Upload and Cropping)

Of course we’ll need to create an HTML form with which users can upload photos:

当然,我们需要创建一个HTML表单,用户可以使用该表单上传照片:

<form action="upload.php" method="post" enctype="multipart/form-data">
 <label for="file">Image:</label>
 <input type="file" name="file" id="file"><br>
 <input type="submit" name="submit" value="Upload and Crop">
</form>

As soon as the user hits the upload button a POST request will be sent to a script which will handle the file upload process and show the uploaded image to the user for cropping. Remember, when uploading files you need to set the form’s enctype attribute to “multipart/form-data”.

用户点击上传按钮后,POST请求将发送到脚本,该脚本将处理文件上传过程,并向用户显示上传的图像以进行裁剪。 请记住,上传文件时,您需要将表单的enctype属性设置为“ multipart / form-data”。

An upload script handles the image upload and resizing the image if required.

上载脚本处理图像上载并根据需要调整图像的大小。

<?php
if (isset($_FILES["file"])) {
    $tmpFile = $_FILES["file"]["tmp_name"];
    $fileName = ... // determine secure name for uploaded file

    list($width, $height) = getimagesize($tmpFile);
    // check if the file is really an image
    if ($width == null && $height == null) {
        header("Location: index.php");
        return;
    }
    // resize if necessary
    if ($width >= 400 && $height >= 400) {
        $image = new Imagick($tmpFile);
        $image->thumbnailImage(400, 400);
        $image->writeImage($fileName);
    }
    else {
        move_uploaded_file($tmpFile, $fileName);
    }
}

You should be very careful while accepting files from users as someone can upload a malicious file to your server if you don’t create a secure upload system. For more information, read the article File Uploads with PHP, paying special attention to the “Security Considerations” section.

在接受来自用户的文件时,您应该非常小心,因为如果您不创建安全的上传系统,则有人可以将恶意文件上传到您的服务器。 有关更多信息,请阅读文章“ 使用PHP上传文件” ,特别注意“安全注意事项”部分。

The getimagesize() function returns a null height and width if the file is not an image, so if the code detects the file is not an image, it simply redirects the user elsewhere. Additionally, you can also check the image type and size of the file using getimagesize(), but in this case we just check if the file is an image based on the null values.

如果文件不是图像,则getimagesize()函数返回的高度和宽度为空,因此,如果代码检测到文件不是图像,则仅将用户重定向到其他位置。 另外,您还可以使用getimagesize()检查文件的图像类型和大小,但是在这种情况下,我们仅根据空值检查文件是否为图像。

Since the script already knows the width and height of the uploaded image at this point, it can determine whether the image should be resized down. If dimensions are more than 400×400px, it’s resized to create a 400×400px thumbnail by calling thumbnailImage(). As I explained earlier, the method takes two parameters: width and height. If you want to maintain the image’s aspect ratio, it’s recommended to pass 0 as one of the arguments.

由于脚本此时已经知道上传图像的宽度和高度,因此可以确定是否应缩小图像尺寸。 如果尺寸大于400×400px,则可以通过调用thumbnailImage()来调整尺寸以创建400×400px的缩略图。 如前所述,该方法采用两个参数:width和height。 如果要保持图像的宽高比,建议将0用作参数之一。

Finally, the resized image is saved by calling writeImage(), or moved with move_uploaded_file() if it was already a suitable size.

最后,调整大小的图像通过调用writeImage()保存,或者如果已经是合适的大小,则使用move_uploaded_file()移动。

The saved image is outputted to the browser so that the user gets a chance to crop it. To allow users to select specific portion of the image, I use a jQuery plugin called ImageAreaSelect. To use the plugin, the jQuery library needs to be available, as well as the plugin’s CSS and JavaScript files.

保存的图像被输出到浏览器,以便用户有机会对其进行裁剪。 为了允许用户选择图像的特定部分,我使用了一个名为ImageAreaSelect的jQuery插件。 要使用插件,需要jQuery库以及插件CSS和JavaScript文件。

<script type="text/javascript" src="scripts/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery.imgareaselect.pack.js"></script>
<link rel="stylesheet" type="text/css" href="css/imgareaselect-default.css">

To initialize the plugin you can use the following code:

要初始化插件,您可以使用以下代码:

selection = $('#photo').imgAreaSelect({
    handles: true,
    instance: true
});

#photo is the id of the image shown to the user. By setting the handles property true you can show resize handles on the selection area, and instance true gets an instance and save it to the variable selection. It’s through selection that you can easily retrieve the selection area later when the user finalizes his cropping.

#photo是显示给用户的图像的ID。 通过将handles属性设置为true,可以在选择区域上显示调整大小的句柄,而instance true获取实例并将其保存到变量selection 。 通过selection ,您可以在用户完成裁剪后轻松地检索选择区域。

getSelection() gives you everything you need. For example, getSelection().width gives you the width of the selection area. Similarly, you can use getSelection().x1 and getSelection().y1 to find the coordinates of the top left-corner of the selection area.

getSelection()为您提供所需的一切。 例如, getSelection().width给出选择区域的宽度。 同样,可以使用getSelection().x1getSelection().y1查找选择区域左上角的坐标。

Putting this all together in a page, you’ll most likely register an onclick callback to a link or button, which the user can click to finalize his selection. When the button is clicked, the selection area width, height, and top-left corner coordinates is retrieved.

将所有内容放到一个页面中,您很可能会在链接或按钮上注册一个onclick回调,用户可以单击该按钮来最终确定选择。 单击按钮后,将检索选择区域的宽度,高度和左上角坐标。

$("#crop").click(function(){
    var s = selection.getSelection();
    var width = s.width;
    var height = s.height;
    var x = s.x1;
    var y = s.y1;
    ...
});

An Ajax request is sent to a cropping script, passing these values as request parameters since they are needed to crop the image through ImageMagick. Additionally, you’ll want to send the image name since the script will need to know the name of the image that it will be cropping.

Ajax请求发送到裁剪脚本,将这些值作为请求参数传递,因为通过ImageMagick裁剪图像需要这些值。 此外,由于脚本需要知道将要裁剪的图像的名称,因此您将需要发送图像的名称。

var request = $.ajax({
    url: "crop.php",
    type: "GET",
    data: {
        x: x,
        y: y,
        height: height,
        width: width,
        image: $("#photo").attr("src")
    }
});

When the request finishes, the image is reloaded so that the new cropped version will be shown in place of the old image.

请求完成后,将重新加载图像,以便将显示新的裁剪版本代替旧图像。

request.done(function(msg) {
    $("#photo").attr("src", msg);
    selection.cancelSelection();
});

When cropping is done, the request returns the name of the cropped image, and the new image is loaded by changing the src attribute.

裁剪完成后,请求将返回裁剪图像的名称,并通过更改src属性来加载新图像。

So what does the cropping script look like?

那么裁剪脚本是什么样的?

<?php
$file = basename($_GET["image"]);
$cropped = "cropped_" . $file;
$image = new Imagick($file);
$image->cropImage($_GET["width"], $_GET["height"], $_GET["x"], $_GET["y"]);
$image->writeImage($cropped);
echo $cropped;

The script first extracts the name of the image that needs to be cropped; the image name will be a full URL in the form of http://example.com/path/image.jpg, but only the image.jpg part is needed. Next, the string “cropped” is prefixed to the original name so that it will look like cropped_image.jpg. This allows the cropped image to be saved without overwriting the original.

该脚本首先提取需要裁剪的图像的名称。 图像名称将是http://example.com/path/image.jpg形式的完整URL,但仅需要image.jpg部分。 接下来,将字符串“ cropped”添加到原始名称的前缀,以使其看起来类似于cropped_image.jpg 。 这样可以保存裁切后的图像而不会覆盖原始图像。

The cropImage() method is used to crop the original image using the four parameters related to the selection area that were sent to the script, and then the cropped image is saved to the new file. The name of the cropped image is then echoed back to the Ajax request for display in the browser.

cropImage()方法用于使用发送到脚本的与选择区域相关的四个参数来裁剪原始图像,然后将裁剪后的图像保存到新文件中。 裁剪后的图像的名称随后回显到Ajax请求,以显示在浏览器中。

结论 (Conclusion)

In this article I created a simple cropping tool to show you the power and easy of use of the ImageMagick extension. You can learn more about it, and be creative and make something more useful using its powerful API. For instance, if you wanted to extend what I’ve presented here, you could give users the option to download their images in multiple sizes. Sample code to accompany this article is available on GitHub to get you started.

在本文中,我创建了一个简单的裁剪工具,以向您展示ImageMagick扩展程序的强大功能和易用性。 您可以了解更多有关它的知识,并可以使用其强大的API发挥创造力并使其更有用。 例如,如果您想扩展我在这里介绍的内容,则可以为用户提供下载多种尺寸图像的选项。 GitHub上提供了本文附带的示例代码,以帮助您入门。

Image via Fotolia

图片来自Fotolia

And if you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like Jump Start PHP.

并且,如果您喜欢阅读这篇文章,您会喜欢Learnable的 向大师学习新鲜技能的地方。 会员可以立即访问所有SitePoint的电子书和交互式在线课程,例如Jump Start PHP

Comments on this article are closed. Have a question about PHP? Why not ask it on our forums?

本文的评论已关闭。 对PHP有疑问吗? 为什么不在我们的论坛上提问呢?

翻译自: https://www.sitepoint.com/crop-and-resize-images-with-imagemagick/

imagemagick使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值