I had the below code that load image from DB. There are more than 600 rows of image has been inserted into the DB. I need the script that can perform these action:
Step 1) Load the image from DB
Step 2) process the image by putting the watermark
Step 3) Output the image to the browser.
I had the below code, that load and show the image. but I don't have any idea how to do the watermark.
$dbconn = #mysql_connect($mysql_server,$mysql_manager_id,$mysql_manager_pw) or exit("SERVER Unavailable");
#mysql_select_db($mysql_database,$dbconn) or exit("DB Unavailable");
$sql = "SELECT type,content FROM upload WHERE id=". $_GET["imgid"];
$result = #mysql_query($sql,$dbconn) or exit("QUERY FAILED!");
$contenttype = #mysql_result($result,0,"type");
$image = #mysql_result($result,0,"content");
header("Content-type: $contenttype");
echo $image;
mysql_close($dbconn);
?>
Please help...
You could ether learn how to manipulate images on your own from php.net or you just get a package like the one below:
http://pear.php.net/package/Image_Tools
(Tools collection of common image manipulations. Available extensions are Blend, Border, Marquee, Mask, Swap, Thumbnail and Watermark.)
How about calling your image the same way you do for the SELECT type, content?
Select the image with an imagepath from your database and then style it so it floats over your information. you could also hardcode the watermark image as it is always the same image you can have repeated. You won't see your information but if you put an opacity on the image, you can see through it:
#img.watermark {
float:left;
opacity:0.1;
z-index:1;
}
This is just one idea on how to do it, but should work quite nicely!
take a look at
imagecopymerge()
from php's graphics librabry, it should do what you're looking for.
http://www.php.net/manual/en/function.imagecopymerge.php
Finally I get the solution, here is the code:
<?php
$dbconn = #mysql_connect($mysql_server,$mysql_manager_id,$mysql_manager_pw) or exit("SERVER Unavailable");
#mysql_select_db($mysql_database,$dbconn) or exit("DB Unavailable");
$sql = "SELECT id, original_name, type, content FROM upload WHERE id=". $_GET["imgid"];
$result = #mysql_query($sql,$dbconn) or exit("QUERY FAILED!");
$fileID = #mysql_result($result,0,"id");
$contenttype = #mysql_result($result,0,"type");
$filename = #mysql_result($result,0,"original_name");
$image = #mysql_result($result,0,"content");
$fileXtension = pathinfo($filename, PATHINFO_EXTENSION);
$finalFileName = $fileID.".".$fileXtension;
// put the file on temporary folder
$filePutPath = "/your/temporary/folder/".$finalFileName;
// put the contents onto file system
file_put_contents($filePutPath, $image);
// get the watermark image
$stamp = imagecreatefrompng('../images/watermark.png');
switch($fileXtension)
{
case 'JPEG':
case 'JPG' :
case 'jpg' :
case 'jpeg':
$im = imagecreatefromjpeg($filePutPath);
break;
case 'gif' :
case 'GIF' :
$im = imagecreatefromgif($filePutPath);
break;
case 'png' :
case 'PNG' :
$im = imagecreatefromgif($filePutPath);
break;
default :
break;
}
list($width, $height) = getimagesize($filePutPath);
// set area for the watermark to be repeated
imagecreatetruecolor($width, $height);
// Set the tile (Combine the source image and the watermark image together)
imagesettile($im, $stamp);
// Make the watermark repeat the area
imagefilledrectangle($im, 0, 0, $width, $height, IMG_COLOR_TILED);
header("Content-type: $contenttype");
// free the memory
imagejpeg($im);
imagedestroy($im);
// delete the file on temporary folder
unlink($filePutPath);
mysql_close($dbconn);
?>
Related
I have the image attached below with these specifics:
Width: 3024px
Height: 4032px
The getimagesize() function returns the opposite:
$size = GetimageSize("test.jpg");
echo "image width: " . $size[0] . ", height: " . $size[1];
image width: 4032, height: 3024
How is this possible?
You can try yourself using the image below.
* UPDATE *
Removed image from the post and added a link to zip file (containing the image) because the image works fine after being processed from stack overflow.
Tinyupload ZIP
Screenshot of the result:
Your image is probably being auto-rotated when you view it. Orientation will play a part in getting the height and width the right way around. This code taken from the php documentation will make sure your image is correctly rotated. There are many other examples in the link to choose from.
<?php
$image = imagecreatefromstring(file_get_contents($_FILES['image_upload']['tmp_name']));
$exif = exif_read_data($_FILES['image_upload']['tmp_name']);
if(!empty($exif['Orientation'])) {
switch($exif['Orientation']) {
case 8:
$image = imagerotate($image,90,0);
break;
case 3:
$image = imagerotate($image,180,0);
break;
case 6:
$image = imagerotate($image,-90,0);
break;
}
}
// $image now contains a resource with the image oriented correctly
?>
Function getimagesize() changes width and height in photos that are landscape orientation (horizontal).
You can use this code:
<?php
$img = "test.jpg";
$exif = exif_read_data($img);
if(empty($exif['Orientation'])) {
list($width, $height, $type, $attr) = getimagesize($img);
}else{
list($height, $width, $type, $attr) = getimagesize($img);
}
?>
But it was fixed automatically in PHP7 and above.
The exif orientation tag cannot be fully trusted, as it really depends on the program or device setting the tag that the correct value is used.
This article explains the exif orientation tag better and why it's a mess. http://www.daveperrett.com/articles/2012/07/28/exif-orientation-handling-is-a-ghetto/
<?php
$image = $_FILES['image'];
//name of new file selected
$imagename = $image['name'];
//name of file in database
$filename = $row['filename'];
//folder to move image
$TARGET_PATH = "../$university/img/users/$category/$username/";
//if imagename in DB is different to image just selected
if ($filename <> $imagename) {
// *** Include the class
include("resize-class.php");
//if the filename in DB different from filename chosen
//delete old image
unlink("../$university/img/users/$oldcategory/$username/$filename");
//create random number and add that to the beginning of new imagename
$uniqueID = uniqid();
$imagetitle = $imagename;
$fileunique = $uniqueID;
$fileunique .= $imagetitle;
$filename = $fileunique;
//upload new selected file
$oldpath = $_FILES['image']['tmp_name'];
// Lets attempt to move the file from its temporary directory to its new home
if (move_uploaded_file($oldpath, $TARGET_PATH)) {
// NOTE: This is where a lot of people make mistakes.
// We are *not* putting the image into the database; we are putting a reference to the file's location on the server
$imagename = $fileunique;
$path = "../$university/img/users/$category/$usernameid/$imagename";
// *** 1) Initialise / load image
$resizeObj = new resize($path);
if (exif_imagetype($path) == IMAGETYPE_JPEG) {
$exif = exif_read_data($path);
$ort = $exif['IFD0']['Orientation'];
switch ($ort) {
case 1: // nothing
break;
case 2: // horizontal flip
$resizeObj->flipImage($public, 1);
break;
case 3: // 180 rotate left
$resizeObj->rotateImage($public, 180);
break;
case 4: // vertical flip
$resizeObj->flipImage($public, 2);
break;
case 5: // vertical flip + 90 rotate right
$resizeObj->flipImage($public, 2);
$resizeObj->rotateImage($public, -90);
break;
case 6: // 90 rotate right
$resizeObj->rotateImage($public, -90);
break;
case 7: // horizontal flip + 90 rotate right
$resizeObj->flipImage($public, 1);
$resizeObj->rotateImage($public, -90);
break;
case 8: // 90 rotate left
$resizeObj->rotateImage($public, 90);
break;
}
}
if (($resizeObj->width > 600) || ($resizeObj->height > 600)) {
// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
$resizeObj->resizeImage(400, 400, 'crop');
// *** 3) Save image
$resizeObj->saveImage($path, 95);
}
//change filename in database
$query = "UPDATE people SET filename=? WHERE id=? AND username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $filename);
$stmt->bindParam(2, $id);
$stmt->bindParam(3, $username);
$stmt->execute();
}
}
?>
I am trying to create a form where users can change an image that they have previously uploaded.
I have posted my code above, it gets as far as 'unlinking' the old image but doesn't seem to do anything after that with no errors.
I am trying to get the code to:
Check the newly selected image name against the name stored in the database
if they are different delete the old image in the folder
upload the new image with random number at the beginning of image name
update the database with the new filename
Any ideas where I'm going wrong? Thanks for your help
Here are some thoughts about code:
as suggested by Aditya use something like sprintf('%s%s', uniqid(), $imagename)
check $_FILES for any error (maybe file is too big)
you are saving image ONLY if it has width or height more then 600 px(not sure if rotating will automatically save the image)
check if you have enough rights to write into directory(maybe you need to create folders first)
I have a client that sends me text messages from his iPhone with images for me to upload into his gallery. I'm trying to create a admin system so I can simply take the images from the texts, go to the admin page on my iPhone and upload the images straight to the gallery.
This would save me tons of time in my day to day work schedule.
Using the provided code. How can I add the following functions:
I would like to compress the file size down to a smaller size if possible, similar to the save to web jpg function in Photoshop. (Most images I get are around 1-3 MB. I would like to get them down to around 150-500kb max)
I would like to automatically change the width to 760px, but keep the aspect ratio so the images are not squished. He sends me landscape and portrait images.
Beings they are iPhone images. They have an extension .JPG (all caps) I would like this to change to .jpg (all lower case.) This is not a deal breaker I would just like to know how to do this for future use.
Either one of these functions would be very helpful, but all 3 would be ideal for my situation.
Here is the code I'm working with?
THIS IS THE FINAL CORRECT CODE FOR UPLOADING AND RESIZING IMAGES PROVIDED By #tman
Make sure you have imagick installed in your php.ini file. Check with your hosting provider to install it.
<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
for($i=0;$i<count($_FILES["image"]["name"]);$i++){
if($_FILES["image"]["name"][$i] != ''){ // don't insert if file name empty
$dataType = mysql_real_escape_string($_POST["dataType"][$i]);
$title = mysql_real_escape_string($_POST["title"][$i]);
$fileData = pathinfo($_FILES["image"]["name"][$i]);
$fileName = uniqid() . '.' . $fileData['extension'];
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $fileName;
if (move_uploaded_file($_FILES["image"]["tmp_name"][$i], $target_path)){ // The file is in the images/gallery folder.
// Insert record into database by executing the following query:
$sql="INSERT INTO images (data_type, title, file_name) "."VALUES('$dataType','$title','$fileName')";
$retval = mysql_query($sql);
///NEW
$size = getimagesize($target_path);
$width=$size[0];
$height=$size[1];
$newwidth = 760;
$newheight = $height*($newwidth/$width);
$pic = new Imagick($target_path);//specify name
$pic->resizeImage($newwidth,$newhight,Imagick::FILTER_LANCZOS,1);
unlink($target_path);
$pic->writeImage($target_path);
$pic->destroy();
///NEW
echo "The image {$_FILES['image']['name'][$i]} was successfully uploaded and added to the gallery<br />
<a href='index.php'>Add another image</a><br />";
}
else
{
echo "There was an error uploading the file {$_FILES['image']['name'][$i]}, please try again!<br />";
}
}
} // close your foreach
?>
uploader.php Original code. Allows me to upload 4 images at once. WORKS!!!
<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
for($i=0;$i<count($_FILES["image"]["name"]);$i++){
if($_FILES["image"]["name"][$i] != ''){ // don't insert if file name empty
$dataType = mysql_real_escape_string($_POST["dataType"][$i]);
$title = mysql_real_escape_string($_POST["title"][$i]);
$fileData = pathinfo($_FILES["image"]["name"][$i]);
$fileName = uniqid() . '.' . $fileData['extension'];
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $fileName;
if (move_uploaded_file($_FILES["image"]["tmp_name"][$i], $target_path)){ // The file is in the images/gallery folder.
// Insert record into database by executing the following query:
$sql="INSERT INTO images (data_type, title, file_name) "."VALUES('$dataType','$title','$fileName')";
$retval = mysql_query($sql);
echo "The image {$_FILES['image']['name'][$i]} was successfully uploaded and added to the gallery<br />
<a href='index.php'>Add another image</a><br />";
}
else
{
echo "There was an error uploading the file {$_FILES['image']['name'][$i]}, please try again!<br />";
}
}
} // close your foreach
?>
FYI, This will allow you to give a unique names to your images, resize the width, but keep the correct aspect ratio and upload multiple file at the same time.
Awesome Stuff!
Like this:
$filelocation='http://help.com/images/help.jpg';
$newfilelocation='http://help.com/images/help1.jpg';
$size = getimagesize($filelocation);
$width=$size[0];//might need to be ['1'] im tired .. :)
$height=$size[1];
// Plz note im not sure of units pixles? & i could have the width and height confused
//just had some knee surgery so im kinda loopy :)
$newwidth = 760;
$newheight = $height*($newwidth/$width)
$pic = new Imagick( $filelocation);//specify name
$pic->resizeImage($newwidth,$newhight,Imagick::FILTER_LANCZOS,1);
//again might have width and heing confused
$pic->writeImage($newfilelocation);//output name
$pic->destroy();
unlink($filelocation);//deletes image
Here is something kind of similar, lets check the size and compress if the image seems that it is too big. I didn't resize it which just requires that you get the dimensions and resize based on desire.
All this is doing is if the file is greater than 250KB compress it to 85% ..
$bytes = filesize($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
//$maxSizeInBytes = 26400; //is 250KB? No? compress it.
if ($bytes > 26400) {
$img = new Imagick($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
$img->setImageCompression(imagick::COMPRESSION_JPEG);
$img->stripImage();
$img->setImageCompressionQuality(85);
$img->writeImage($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
}
OR:
// resize with imagejpeg ($image, $destination, $quality); if greater than byte size KB
// Assume only supported file formats on website are jpg,jpeg,png, and gif. (any others will not be compressed)
$bytes = filesize($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
//$maxSizeInBytes = 26400; //is gtr than 250KB? No? compress it.
if ($bytes > 26400) {
$info = getimagesize($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
$quality = 85; //(1-100), 85-92 produces 75% quality
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
imagejpeg($image,$inventory_path.DIRECTORY_SEPARATOR.$this->uploadName,$quality);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
imagejpeg($image,$inventory_path.DIRECTORY_SEPARATOR.$this->uploadName,$quality);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName
imagejpeg($image,$inventory_path.DIRECTORY_SEPARATOR.$this->uploadName,$quality);
}
}
thanks for taking the time to read this. I have a form with 35 file input boxes as part of a CMS for my customer to upload 35 pictures of each his products. The breakdown of that is 7 pictures of the black version, 7 pictures of the blue, 7 pictures of the grey, 7 pictures of the red, and 7 pictures of the white version of each product. So that's 35 total pictures he needs to upload. Additionally, for each of those files that he uploads, a smaller "thumbnail" sized picture needs to be made. I have a file upload script that I always use that works beautifully - when there's one file to upload. I'm not sure how to apply it in this case for 35 files. Each input box has a unique name (black1, black2...black7, blue1, blue2...blue7, etc) so, technically I could repeat the upload code 35 times with the unique name of each file input box to do this, but that is obvoiusly extremely inefficient. I'm hoping someone here can help me out with a better solution.
An additional requirement is that the names of the files be stored in a database. All of the filenames of the black pictures should be put into a string, separated by commas, and stored in the blackpics column of the database. All of the filenames of the blue pictures should be put into a string, separated by commas, and stored in the bluepics columns of the database. And so on for the grey, red, and white pictures.
Here is the code that I have now to upload one file. It gets the file from input box "file", checks that it's of the right extension (an image file), checks the filesize, creates a random file name with a random number and timestamp, creates a thumbnail (448px x 298px - big thumbnail, I know), checks that the original image uploaded was of the right dimensions (873px x 581px), and if everything is okay, I end up with the big file saved in ../images/store/big/ and the thumb saved in ../images/store/small/. They both have the same filename, they're just stored in different directories. Temporary files are deleted and all that, and if there are any errors, the files are deleted. As I said, this works great for one file.
So what I need to do is modify the code so that it does all of this for input box "black1", "black2"..."black7", then saves all the filenames into a string (black1.jpg,black2.jpg,black3.jpg,black4.jpg,black5.jpg,black6.jpg,black7.jpg) which I can then store in the 'blackpics' column of the database. Same for the blue, grey, red, and white. I don't need any help with the database part. I'm thinking that I need to create a function containing the file upload script that returns the filename. Then call that function 35 times, one for each of the input boxes. But I could be wrong.
If anyone could offer me any assistance, I would greatly appreciate it. Here is the code for the upload script:
<?php
$filename = $_FILES["file"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$filesize = $_FILES["file"]["size"];
$allowed_file_types = array('.jpg','.gif','.png', '.JPG');
if (in_array($file_ext,$allowed_file_types) && ($filesize < 1024000)) {
// rename file
$rand = rand(1,100000000);
$time = time();
$newfilename = $rand . $time . $file_ext;
if (file_exists("../images/store/big/" . $newfilename)) {
// file already exists error
$err[] = "You have already uploaded this file.";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "../images/store/big/" . $newfilename);
$pathToImage = '../images/store/big/' . $newfilename;
$pathToThumb = '../images/store/small/' . $newfilename;
$last4 = substr($pathToImage, -4);
switch(strtolower($last4)) {
case '.jpeg':
$img = imagecreatefromjpeg($pathToImage);
break;
case '.jpg':
$img = imagecreatefromjpeg($pathToImage);
break;
case '.png':
$img = imagecreatefrompng($pathToImage);
break;
case '.gif':
$img = imagecreatefromgif($pathToImage);
break;
default:
exit('Unsupported type: '. $pathToImage);
}
$max_width = 448;
$max_height = 298;
// Get current dimensions
$old_width = imagesx($img);
$old_height = imagesy($img);
// Calculate the scaling we need to do to fit the image inside our frame
$scale = min($max_width/$old_width, $max_height/$old_height);
// Get the new dimensions
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
$tmp_img = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
switch(strtolower($last4)) {
case '.jpeg':
imagejpeg($tmp_img, $pathToThumb);
break;
case '.jpg':
imagejpeg($tmp_img, $pathToThumb);
break;
case '.png':
imagepng($tmp_img, $pathToThumb);
break;
case '.gif':
imagegif($tmp_img, $pathToThumb);
break;
default:
exit('Unsupported type: '. $pathToImage);
}
imagedestroy($tmp_img);
imagedestroy($img);
}
} elseif (empty($file_basename)) {
$err[] = "Select a file to upload";
} elseif ($filesize > 1024000) {
$err[] = "File size limit exceeded";
} else {
$err[] = "File type not allowed";
unlink($_FILES["file"]["tmp_name"]);
}
list($width, $height) = getimagesize("../images/store/big/$newfilename");
if ($width != "873" || $height != "581") {
$err[] = "File dimensions error";
unlink("../images/store/big/$newfilename");
unlink("../images/store/small/$newfilename");
}
?>
And in the body I have the file upload fields as so...
<input type="file" name="black1" disabled="1">
<input type="file" name="black2" disabled="1">
...
<input type="file" name="black7" disabled="1">
<input type="file" name="blue1" disabled="1">
<input type="file" name="blue2" disabled="1">
...
<input type="file" name="blue7" disabled="1">
and so on for grey, red, and white.
Like I said, if anyone can help me out, I would greatly appreciate it. And if you made it all the way down here, thanks again for taking the time to read all of this.
First don't use dimensions for images. Dimensions do not say much about the size of the image. And the size matters for displaying the image on a website, not the dimensions.
Second why not use a multipart uploading form? See here. And then your client could select the images colourwise and upload them with one selection, which would reduce the clicks from 35 to seven. Or if you trust your client to be more tech-savvy: Use only one input field and instruct him to name his files in a specific way. Like "b_[name of file].[extension]" for a black image. Then use your favourite string searching method - for example RegEx - to identify the images classes.
I have a question about the images displaying using a function getImage_w($image,$dst_w), which takes the image URL ($image) and the destination width for this image ($size). Then it re-draws the image changing its height according to the destination width.
That's the function (in libs/image.php file):
function getImage_w($image,$w){
/*** get The extension of the image****/
$ext= strrchr($image, ".");
/***check if the extesion is a jpeg***/
if (strtolower($ext)=='.jpg' || strtolower($ext)=='.jpeg'){
/***send the headers****/
header('Content-type: image/jpeg');
/**get the source image***/
$src_im_jpg=imagecreatefromjpeg($image);
/****get the source image size***/
$size=getimagesize($image);
$src_w=$size[0];
$src_h=$size[1];
/****calculate the distination height based on the destination width****/
$dst_w=$w;
$dst_h=round(($dst_w/$src_w)*$src_h);
$dst_im=imagecreatetruecolor($dst_w,$dst_h);
/**** create a jpeg image with the new dimensions***/
imagecopyresampled($dst_im,$src_im_jpg,0,0,0,0,$dst_w,$dst_h,$src_w,$src_h);
imagejpeg($dst_im);
}
In a file imagetest.php I have this code portion:
<?php
require 'libs/image.php';
echo '<h1>HELLO WORLD : some html</h1>
<img src="'.displayImg_w('http://www.sanctius.net/wp-content/uploads/2010/05/Avatar-20.jpg',200).'">
';
In the past, I used to write the URL with $_GET paramers defining the image. But now , I want to use the function directly in my code.
The problem is that the image is displaying correctly, but the Hello World HTML code is not translated by the browser (I know that the header are already sent by the first code) But I want to know how to display the image correctly without affecting the html code. and also without using get parameters that change the URL of the image to this undesired form :
libs/image.php?image=http://www.example.com/image&width=200
After my earlier, totally wrong answer, I hope to make up for it with this. Try this code:
<?php
function getImage_w($image,$w){
// Get the extension of the file
$file = explode('.',basename($image));
$ext = array_pop($file);
// These operations are the same regardless of file-type
$size = getimagesize($image);
$src_w = $size[0];
$src_h = $size[1];
$dst_w = $w;
$dst_h = round(($dst_w/$src_w)*$src_h);
$dst_im = imagecreatetruecolor($dst_w,$dst_h);
// These operations are file-type specific
switch (strtolower($ext)) {
case 'jpg': case 'jpeg':
$ctype = 'image/jpeg';;
$src_im = imagecreatefromjpeg($image);
$outfunc = 'imagejpeg';
break;
case 'png':
$ctype = 'image/png';;
$src_im = imagecreatefrompng($image);
$outfunc = 'imagepng';
break;
case 'gif':
$ctype = 'image/gif';;
$src_im = imagecreatefromgif($image);
$outfunc = 'imagegif';
break;
}
// Do the resample
imagecopyresampled($dst_im,$src_im,0,0,0,0,$dst_w,$dst_h,$src_w,$src_h);
// Get the image data into a base64_encoded string
ob_start();
$outfunc($dst_im);
$imgdata = base64_encode(ob_get_contents()); // Don't use ob_get_clean() in case we're ever running on some ancient PHP build
ob_end_clean();
// Return the data so it can be used inline in HTML
return "data:$ctype;base64,$imgdata";
}
echo '<h1>HELLO WORLD : some html</h1>
<img src="'.getImage_w('http://www.sanctius.net/wp-content/uploads/2010/05/Avatar-20.jpg',200).'" />
';
?>
This basically is not possible. The webbrowser requests the HTML page and expects HTML. Or it requests an image and expects an image. You cannot mix both in one request, just because only one Content-Type can be valid.
However, you can embed the image in HTML using data URI:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4/8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">
Be aware that the base64 encoding is quite ineffective, so make sure you definitly compress your output, if the browser supports it, using for example gzip.
So for you it likely looks like the following:
echo '<img src="data:image/jpeg;base64,' . base64_encode(displayImg_w('http://www.sanctius.net/wp-content/uploads/2010/05/Avatar-20.jpg',200)) . '">';
And make sure displayimg_w() does not output a header anymore.
Furthermore, displayimg_w() needs to be adjusted at the end to return the image data as string rather than direct output:
ob_start();
imagejpeg($dst_im);
return ob_get_flush();