开发者

Thumbnailing and then Saving as a Blob with PHP in Wordpress

开发者 https://www.devze.com 2022-12-23 08:31 出处:网络
The below code seems like it should work; however, the blob in the database only contains 0 after the function is run. Does the below code look accurate? If not how can I fix it?

The below code seems like it should work; however, the blob in the database only contains 0 after the function is run. Does the below code look accurate? If not how can I fix it?

$tmpName  = $_FILES['p开发者_JAVA百科icture']['tmp_name'];

$fp      = fopen($tmpName, 'r');
$binary = fread($fp, filesize($tmpName));
fclose($fp);

$originalImage = imagecreatefromstring($binary);
$tempImage = imagecreate(100,100);
imagecopyresized($tempImage,$originalImage,0,0,0,0,100,100);
ob_start();
imageJPEG($tempImage);
$thumbnail = ob_get_contents();
ob_end_clean();

$wpdb->query("UPDATE ".$wpdb->prefix."items SET picture = $thumbnail WHERE id=$id'");

Thank :)!


You would probably want to send the blob/picture data to your DB as hex, as it is the most efficient method:

if ( is_uploaded_file($_FILES['picture']['tmp_name']) ) {
    $originalImage = imagecreatefromjpeg($_FILES['picture']['tmp_name']);
    $thumbImage = imagecreatetruecolor(100, 100);
    imagecopyresized($thumbImage, $originalImage, 0, 0, 0, 0, 100,100);

    imagedestroy($originalImage); // Free the memory as soon as possible

    ob_start();
    imagejpeg( $thumbImage, NULL, JPEG_QUALITY);
    $thumbData = ob_get_contents();
    ob_end_clean();

    imagedestroy($thumbImage);


    $wpdb->query("UPDATE ".$wpdb->prefix."items SET picture = x'".bin2hex($thumbData)."' WHERE id=$id'");
}

note the x'".bin2hex($thumbData)."' the x marks the contents of the string as hex.

Please note:
There is a lot of debate about if it is a good idea to store images in the Database or not. The general consensus is that it is a bad idea, except when:

  1. Your images are less than 2MB in size
  2. You intend to store no more tan 1GB in total (and even at 1GB you are stretching it).

In all other cases, store the image on disk and store the location of said image in your database.


You definitely need to add quotes; and then I guess you would have to mysql_real_escape_string() the whole thumbnail code.

$thumbnail = mysql_real_escape_string($thumbnail);

$wpdb->query("UPDATE ".$wpdb->prefix."items SET picture = '$thumbnail' WHERE 
             id='$id'");
0

精彩评论

暂无评论...
验证码 换一张
取 消