user1187135
user1187135

Reputation:

I can't output the new image after imagecopyresampled

Can someone help me out.. I want to check if my resize is working correctly, but I can't output the imagecopyresampled image. It outputs a bunch of weird characters right now.

//uploading image
    $image_file = $_FILES['image']['tmp_name'];
    $image_size = @getimagesize($image_file);

    $image_mime = $image_size['mime'];
    $image_width = $image_size['0'];
    $image_height  = $image_size['1'];
    $image_ratio = $image_width/$image_height;

    //not an image
    if ($image_size === false) {
        error('1');
    } 

    //check to see if valid image type
    switch ($image_mime){
        case 'image/jpg':
        case 'image/jpeg':
        case 'image/pjpeg':
            $image_file = @imagecreatefromjpeg($image_file);
            break;

        case 'image/png':
            $image_file = @imagecreatefrompng($image_file);
            break;

        default: 
            error('2');
            break;
    }

    if ($image_width < 450 || $image_height < 350) {
        //image too small
        error('3');
    } 

    if ($image_ratio >= 1){
        //resize by height
        $height = 350;
        $ratio = $height/$image_height;
        $width = $image_width * $ratio;
    } else {
        //resize by width
        $width = 450;
        $ratio = $width/$image_width;
        $height = $image_height * $ratio;
    }

    //get the center axis
    $x_center = ($image_width - $width)/2;
    $y_center = ($image_height - $height)/2;

    $new_image = imagecreatetruecolor($width, $height);
    imagecopyresampled($new_image, $image_file, 0, 0, $x_center, $y_center, $width, $height, $image_width, $image_height);

    imagepng($new_image);


    exit();

Upvotes: 0

Views: 660

Answers (1)

deceze
deceze

Reputation: 522135

Those weird character are the image as output in binary. Your browser doesn't know that that's supposed to be an image, because you did not tell it. Add a header before the image output to inform the browser what kind of data it's dealing with:

header('Content-Type: image/png');

Upvotes: 1

Related Questions