dongzhen6554 2016-11-14 08:53
浏览 38
已采纳

如何使用php将图像文件作为数据url读取

In javascript, I read the file data by binding the on-change method to the file input and saving the file data into another input using the following code

$("#release_cover_custom").on('change', function (evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

        // Only process image files.
        if (!f.type.match('image.*')) {
            continue;
        }

        var reader = new FileReader();

        // Closure to capture the file information.
        reader.onload = (function (theFile) {
            return function (e) {
                $("#release_cover_custom_data").val(e.target.result);
            };
        })(f);

        // Read in the image file as a data URL.
        reader.readAsDataURL(f);
    }


});

why i use the above code?, to store the image data, because i have a form where i provide settings for the email template that would be sent later and there i have to provide the background image to be used inside the email, i need to preview the email with all the settings and along with the background image provided to upload before saving the form or uploading the image, so i read the image data, save it to an input and then open a modal window to preview email and post all the necessary variables there including the image data which is then used in the following way inside the css to apply the background-image like below in my php view file

background-image:url('" . $background_image . "') !important;

Now i want to do the achieve the same thing via php, means if i have the image saved to a path and i want to read the image data and use it in the same way i did using javascript to futher pass it to the css property,

i tried to use base64_encode(file_get_contents('path/to/file'))

but the encoding seems to be different for the image data, as the background image is not shown should i be using some other method to achieve it in php.

  • 写回答

1条回答 默认 最新

  • douqiang6036 2016-11-14 20:09
    关注

    @quagaar reply helped me solve the problem and replaced the following

    $background_image=base64_encode(file_get_content('/path/to/file'));
    

    with

    $background_image='data:image/png;base64,'.base64_encode(file_get_content('/path/to/file'));
    

    and everything works fine as expected.

    EDIT:

    between i was dealing with images only and if you are working with Images only and you need mime type (e.g. for headers, or like my case), then this is a fast and reliable technique:

    $file = 'path/to/image.jpg';
    $image_mime = image_type_to_mime_type(exif_imagetype($file));
    

    It will output true image mime type even if you rename your image file.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?