如何使用cropit jquery插件和php裁剪并上传照片

13

我最近发现了一个叫做cropit的照片剪裁插件。演示在这里。我想做的事情是获取剪裁后的照片,将其名称上传到MySQL数据库并使用PHP保存到目录中。

到目前为止,我只有以下HTML代码:

<form method="POST">
    <div class="image-editor">
        <div class="cropit-image-preview-container">
            <div class="cropit-image-preview"></div>
        </div>
            <div class="image-size-label">
            Resize image
        </div>
        <input type="range" class="cropit-image-zoom-input">
        <input type="hidden" name="image-data" class="hidden-image-data" />
        <button type="submit">Submit</button>
    </div>
</form>

jQUERY :

    $('form').submit(function() {
        // Move cropped image data to hidden input
        var imageData = $('.image-editor').cropit('export');
        $('.hidden-image-data').val(imageData);

        // Print HTTP request params
        var formValue = $(this).serialize();
        $('#result-data').text(formValue);

        // Prevent the form from actually submitting
        return false;
    });

我需要帮助的只是php设置代码,因为当我裁剪照片并选择提交时,jQuery会返回序列化代码,而通常我不熟悉这个代码。以下是jQuery返回的序列化代码的一些字符:

image-data=data%3Aimage%2Fpng%3Bbase64%2CiVBORw0KGgoAAAANSUhE...

2
看看这个很棒的库-Intervention Image-,你不会后悔的。它可以作为独立库使用,也可以作为Laravel包使用。 - ozanmuyes
1
完全可以推荐Intervention Image。下面答案中的代码无法正常工作(空白图像),但是一旦我使用了Intervention,它就完美地工作了。 - AndyDunn
接受的答案对我没用,但是这个 Intervention Image 十分有效。 - dmirkitanov
2个回答

14

1. 保存base64编码的图像

    <?php
    //save your data into a variable - last part is the base64 encoded image
    $encoded = "data%3Aimage%2Fpng%3Bbase64%2CiVBORw0KGgoAAAANSUhE";

    //decode the url, because we want to use decoded characters to use explode
    $decoded = urldecode($encoded);

    //explode at ',' - the last part should be the encoded image now
    $exp = explode(',', $decoded);

    //we just get the last element with array_pop
    $base64 = array_pop($exp);

    //decode the image and finally save it
    $data = base64_decode($base64);
    $file = 'data.png';

    //make sure you are the owner and have the rights to write content
    file_put_contents($file, $data);

2. 获取base64编码图像的文件名

    $encoded = "data%3Aimage%2Fpng%3Bbase64%2CiVBORw0KGgoAAAANSUhE";
    $decoded = urldecode($encoded);
    $exp = explode(';', $decoded);
    $exp = explode(':', $exp[0]);
    $image = array_pop($exp);
    echo ($image);

非常好的回答。我有一个问题,如何获取照片的扩展名,因为它不总是png?我问这个问题的原因是因为我将把它添加到文件名的末尾。 - this.Tony
图片名称包含它。您可以像我的示例一样再次使用explode()。请注意,给定的文件扩展名不必与文件的MIME类型匹配。 - oshell
我们如何将jQuery数据保存在PHP变量中? - Jaskaran singh Rajal
1
@JaskaransinghRajal 你需要使用ajax并设置POST或GET参数。 - oshell
我注意到即使我上传了一个“jpg”文件,我仍然收到的编码是“data:image/png;base64”。如果它是一个“jpg”,它不应该显示“data:image/jpg;base64”吗? - Cesar Bielich
它获取已上传图像的MIME类型。这可能与文件扩展名不同。两种格式在开头都有易于识别的签名,因此浏览器可以识别出图像的类型,无论文件扩展名是什么。 - oshell

-2

我成功让Hosch Nok的答案工作了,方法是不解码编码数据。

$decoded = urldecode($encoded);

但是直接使用$encoded变量。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接