eeeltie
eeeltie

Reputation: 1

How can i INSERT the result of this function to MYSQL?

one of the input tags in my form gets a URL of a png image. here i'm resizing the image using first the "imagescale()", and then the "imagecrop()" function. i'm trying to "INSERT" the result of the "imagecrop()" into the "image" field as an image file. i changed the "image" row in my database to a "BLOB". but doesn't seem to work. i have to point out that i'm a beginner. any ideas ?

if (isset($_POST['sub'])) {
$title = $_POST['title'];
$image = $_POST['image'];
$content = $_POST['content'];
$tag = $_POST['tag'];
$author = $_POST['author'];
$date = date('F j, Y');

$im = imagecreatefrompng($image);
$img = imagescale($im, -1, 170);
$im2 = imagecrop($img, ['x' => 48, 'y' => 0, 'width' => 145, 'height' => 170]);

$result = $conn->prepare('INSERT INTO posts SET title=?, image=?, content=?, tag=?, author=?, date=?');
$result->bindValue(1, $title);
$result->bindValue(2, $im2);
$result->bindValue(3, $content);
$result->bindValue(4, $tag);
$result->bindValue(5, $author);
$result->bindValue(6, $date);
$result->execute();

Upvotes: 0

Views: 33

Answers (1)

Bill Karwin
Bill Karwin

Reputation: 562661

The $im2 variable is a GdImage object, not the bytes of any image format. You need to fetch the image content from the GdImage object, which means you need to choose an image format (e.g. jpeg, png, etc.).

Here's an example, copied from a user comment on this documentation page: https://www.php.net/manual/en/function.imagepng.php

ob_start();
imagepng($image);
$image_data = ob_get_contents();
ob_end_clean();

This seems like an awkward method to just capture the image content. You would think there should be a function to render an image to a particular format and just return that content, instead of forcing us to use output buffer capture techniques. But that's PHP for you...

Upvotes: 1

Related Questions