douri4459 2016-11-22 13:36
浏览 75

imagecopyresampled()我的图像在调整大小后变成黑色 - CakePhp3

This when I send ajax request to my controller to crop and resize it, instead it resize it but my image turns black. I even tried adding header so that my browser can understands that it is a valid image file format. Where I am missing?

**My ajax call to controller**
<script type="text/javascript">
        jQuery(document).ready(function(){

        jQuery('#change-pic').on('click', function(e){
            jQuery('#changePic').show();
            jQuery('#change-pic').hide();

        });

        jQuery('#photoimg').on('change', function()   
        { 
            jQuery("#preview-avatar-profile").html('');
            jQuery("#preview-avatar-profile").html('Uploading....');
            jQuery("#cropimage").ajaxForm(
            {
            target: '#preview-avatar-profile',
            success: function() { 

                    jQuery('img#photo').imgAreaSelect({
                    aspectRatio: '1:1',
                    onSelectEnd: getSizes,
                });

                jQuery('#image_name').val(jQuery('#photo').attr('file-name'));
                }
            }).submit();

        });

        jQuery('#btn-crop').on('click', function(e){
        e.preventDefault();
        params = {
                //targetUrl: 'profile.php?action=save',
                targetUrl: 'http://172.16.0.60/cakephp/users/croppedimage',
                //action: 'save',
                x_axis: jQuery('#hdn-x1-axis').val(),
                y_axis : jQuery('#hdn-y1-axis').val(),
                x2_axis: jQuery('#hdn-x2-axis').val(),
                y2_axis : jQuery('#hdn-y2-axis').val(),
                thumb_width : jQuery('#hdn-thumb-width').val(),
                thumb_height:jQuery('#hdn-thumb-height').val()
            };

            saveCropImage(params);
        });



        function getSizes(img, obj)
        {
            var x_axis = obj.x1;
            var x2_axis = obj.x2;
            var y_axis = obj.y1;
            var y2_axis = obj.y2;
            var thumb_width = obj.width;
            var thumb_height = obj.height;
            if(thumb_width > 0)
                {

                    jQuery('#hdn-x1-axis').val(x_axis);
                    jQuery('#hdn-y1-axis').val(y_axis);
                    jQuery('#hdn-x2-axis').val(x2_axis);
                    jQuery('#hdn-y2-axis').val(y2_axis);
                    jQuery('#hdn-thumb-width').val(thumb_width);
                    jQuery('#hdn-thumb-height').val(thumb_height);

                }
            else
                alert("Please select portion..!");
        }

        function saveCropImage(params) {

        jQuery.ajax({
            url: params['targetUrl'],
            cache: false,
            dataType: "html",
            data: {
                action: params['action'],
                id: jQuery('#hdn-profile-id').val(),
                 t: 'ajax',
                                    w1:params['thumb_width'],
                                    x1:params['x_axis'],
                                    h1:params['thumb_height'],
                                    y1:params['y_axis'],
                                    x2:params['x2_axis'],
                                    y2:params['y2_axis'],
                                    image_name :jQuery('#image_name').val()
            },
            type: 'Post',
           // async:false,
            success: function (response) {
                    jQuery('#changePic').hide();
                    jQuery('#change-pic').show();
                    jQuery(".imgareaselect-border1,.imgareaselect-border2,.imgareaselect-border3,.imgareaselect-border4,.imgareaselect-border2,.imgareaselect-outer").css('display', 'none');

                    jQuery("#avatar-edit-img").attr('src', response);
                    jQuery("#preview-avatar-profile").html('');
                    jQuery("#photoimg").val('');
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert('status Code:' + xhr.status + 'Error Message :' + thrownError);
            }
        });
        }
        });
    </script>

This is one first when I upload the image and preview it.

 public function wall()
    {
        $post = isset($_POST) ? $_POST: array();
        $max_width = "500"; 
        $userId = isset($post['hdn-profile-id']) ? intval($post['hdn-profile-id']) : 0;
        //   $path = 'http://172.16.0.60/cakephp/webroot/img/tmp';
        $path = WWW_ROOT.'img/tmp/' ;

        $valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
        $name = $_FILES['photoimg']['name'];
        $size = $_FILES['photoimg']['size'];
        if(strlen($name))
        {
            list($txt, $ext) = explode(".", $name);
            if(in_array($ext,$valid_formats))
            {
                if($size<(1024*1024)) // Image size max 1 MB
                {
                    $actual_image_name = 'avatar' .'_'.$userId .'.'.$ext;
                    $filePath = $path .'/'.$actual_image_name;


                    $tmp = $_FILES['photoimg']['tmp_name'];


                    if(move_uploaded_file($tmp, $filePath))
                    {
                        // /$this->setPassword($this->request->data['password']);
                        $width = $this->getWidth($filePath);
                        $height = $this->getHeight($filePath);
                        //Scale the image if it is greater than the width set above
                        if ($width > $max_width)
                        {
                            $scale = $max_width/$width;
                            $uploaded = $this->resizeImage($filePath,$width,$height,$scale);
                        }
                        else
                        {
                            $scale = 1;
                            $uploaded = $this->resizeImage($filePath,$width,$height,$scale);
                        }

/*
                        echo "<img id='photo' file-name='".$actual_image_name."' class='' src='".'file://'.$filePath.'?'.time()."' class='preview'/>";
*/
                        $mypath = '/cakephp/img/tmp/'.$actual_image_name;
                        echo "<img id='photo' file-name='".$actual_image_name."' class='' src='".$mypath."' class='preview'/>";

                    }
                    else
                    echo "failed";
                }
                else
                echo "Image file size max 1 MB"; 
            }
            else
            echo "Invalid file format.."; 
        }
        else
        echo "Please select image..!";
        exit;
    }

My Controller code where I use the function imagecopyresampled() but idk where I am going wrong.?
Any solution

public function croppedimage()
    {
        header('Content-Type: image/png');
        $post = isset($_POST) ? $_POST: array();
        $userId = isset($post['id']) ? intval($post['id']) : 0;
        //$path ='\images\uploads\tmp';
        $path = WWW_ROOT.'img/tmp/uploads/' ;

        $t_width = 300; // Maximum thumbnail width
        $t_height = 300;    // Maximum thumbnail height

        if(isset($_POST['t']) and $_POST['t'] == "ajax")
        {
            extract($_POST);

            //$img = get_user_meta($userId, 'user_avatar', true);
            //$filePath = $path .'/'.$actual_image_name;

            $imagePath = $path.$_POST['image_name'];
            $ratio = ($t_width/$w1); 
            $nw = ceil($w1 * $ratio);
            $nh = ceil($h1 * $ratio);
            $nimg = imagecreatetruecolor($nw,$nh);
            $im_src = imagecreatefromjpeg($imagePath);
            imagecopyresampled($nimg,$im_src,0,0,$x1,$y1,$nw,$nh,$w1,$h1);
            imagejpeg($nimg,$imagePath,90);

        }
    echo $imagePath.'?'.time();;
    exit(0);    
        die();
    }
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 winform的chart曲线生成时有凸起
    • ¥15 msix packaging tool打包问题
    • ¥15 finalshell节点的搭建代码和那个端口代码教程
    • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
    • ¥15 Centos / PETSc / PETGEM
    • ¥15 centos7.9 IPv6端口telnet和端口监控问题
    • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
    • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
    • ¥20 海浪数据 南海地区海况数据,波浪数据
    • ¥20 软件测试决策法疑问求解答