Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the header( content-type: image/<ANY IMG FORMAT>)

The php file that handles the images I display only allows one image format, either .jpg, .png, .bmp, etc but not all. The imageName stores the file name of the image stored in the database including its format. this is my code, so far it doesn't work yet and I'm not sure if that's allowed. Can you help me fix it please?

$con = mysqli_connect("localhost","root","","tickets");
$ticket = 109;
$result = mysqli_query($con,"SELECT image, imageName FROM tix WHERE tktNum=$ticket");


while($row = mysqli_fetch_array($result))
{
    $image = $row['image'];
    $imageName = $row['imageName'];
    $format = substr( $imageName, -3 ); //gets the last 3 chars of the file name, ex: "photo1.png" gets the ".png" part
    header('content-type: image/' . $format);
}
like image 768
user3663049 Avatar asked May 23 '14 02:05

user3663049


People also ask

Which code will set Content-Type header to image PNG?

php header ('Content-Type: image/png'); $im = @imagecreatetruecolor(120, 20) or die('Cannot Initialize new GD image stream'); $text_color = imagecolorallocate($im, 233, 14, 91); imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color); imagepng($im); imagedestroy($im); ?>

What is header Content-Type PNG?

The Content-Type header is used to indicate the media type of the resource. The media type is a string sent along with the file indicating the format of the file. For example, for image file its media type will be like image/png or image/jpg, etc. In response, it tells about the type of returned content, to the client.

What is Content-Type header in REST API?

The Content-Type field in the HTTP headers indicates in which format the data is sent to, or returned by, the HTTP methods of the Rule Execution Server REST API.


2 Answers

I just used this, just indicating it's an image but without specifying image type.

header("Content-type: image");

It seems to be working just fine regardless of file type. I tested with IE, Firefox, Safari and the Android browser.

like image 190
John Avatar answered Oct 30 '22 10:10

John


The solution is to read in the file and decide which kind of image it is and basednd on it send out the appropriate header.

$filename = basename($file);
$file_extension = strtolower(substr(strrchr($filename,"."),1));

switch( $file_extension ) {
    case "gif": $ctype="image/gif"; break;
    case "png": $ctype="image/png"; break;
    case "jpeg":
    case "jpg": $ctype="image/jpeg"; break;
    case "svg": $ctype="image/svg+xml"; break;
    default:
}

header('Content-type: ' . $ctype);
like image 20
D555 Avatar answered Oct 30 '22 09:10

D555