如何获得不同格式的图像

时间:2019-09-07 02:24:11

标签: php

我有这个功能,可以获取用户图像,并对其进行jpg硬编码,但是有些用户上载了png,有些用户上传了gif,如何使它适用于所有格式?

 function get_avatar($image, $user_id, $account) 
 {
   $imgurl =$_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["HTTP_HOST"] . "/files/pictures/picture-" . ($user_id) . ".jpg";

   if (!is_imgurl_good($imgurl)) {
     $imgurl =$_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["HTTP_HOST"] . "/sites/all/themes/simple_custom/user.png";
   }
   return $imgurl;
 }

function is_imgurl_good($imgurl) {
if (@getimagesize($imgurl))
  return true;//Check that if this returns false the previous function works
  //return false; //Comment out the first line and uncomment this one to show the reverse case.
  
}

2 个答案:

答案 0 :(得分:0)

是的,您可以限制

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

您应该提供这样的图片类型

if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }

see working example here for your better understand

答案 1 :(得分:0)

您只是喜欢这个示例

$sql = "SELECT picture FROM table_name where id=1";
$result = $conn->query($sql);

if ($result->num_rows == 1) {
    // output data of each row
    $row = $result->fetch_assoc();
   $user_picture=$row["picture"];


 $imgurl =$_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["HTTP_HOST"] . "/files/pictures/".$user_picture."";