Stuart Brian Stuart Brian - 1 month ago 17
HTML Question

Php image resize in output

I have this php function to resize image according to where i need it and the size i wish to display.
But my problem is how to i set it to display resized image in html image element without setting the php content type to image?
If i set content type to image it will display the image in the whole page and if i remove it it will output long unknown characters, how do i do this to get what i want?

<?php
function CroppedThumbnail($imagename, $imgwidth, $imgheight){
// Set a maximum height and width
$width = $imgwidth;
$height = $imgheight;
// Content type
//header('Content-Type: image/jpeg');
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($imagename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($imagename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagejpeg($image_p, $imagename, 100);
return $imagename;
}

$filename1 = 'http://static1.techlosofy.com/wp-content/uploads/YouTube-Logo-Large.jpg';
$filename2 = 'http://static1.techlosofy.com/wp-content/uploads/YouTube-Logo-Small.jpg';
echo '<img data="image1" src="'.CroppedThumbnail($filename1, 100, 100).'"/>';
echo '<img data="image2" src="'.CroppedThumbnail($filename2, 100, 100).'"/>';
?>


I want to resize any image that i call this function on

Answer
$newFile = 'images/newFile.jpg';

imagejpeg($image_p, $newFile, 100);

return '/' . $newFile;

I have edited your code:

<?php
function CroppedThumbnail($imagename, $imgwidth, $imgheight){
// Set a maximum height and width
    $width = $imgwidth;
    $height = $imgheight;
// Content type
//header('Content-Type: image/jpeg');
// Get new dimensions
    list($width_orig, $height_orig) = getimagesize($imagename);
    $ratio_orig = $width_orig/$height_orig;
    if ($width/$height > $ratio_orig) {
        $width = $height*$ratio_orig;
    } else {
        $height = $width/$ratio_orig;
    }
// Resample
    $image_p = imagecreatetruecolor($width, $height);
    $image = imagecreatefromjpeg($imagename);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
    $newFileName = 'images/newFile.jpg';
    imagejpeg($image_p, $newFileName, 100);

    return '/' . $newFileName;
}
$filename1 = 'http://static1.techlosofy.com/wp-content/uploads/YouTube-Logo-Large.jpg';
echo '<img data="image1" src="'.CroppedThumbnail($filename1, 100, 100).'"/>';
?>
Comments