开发者

Resize image directly from Rackspace Cloud Files 'object' without downloading?

I have moved my images to Rackspace Cloud Files and am using their PHP API. I am trying to do the following:

  1. Get an image from my "originals" container
  2. Resize it, sharpen it, etc.
  3. Save the resized image to the "thumbs" container

My problem is with #2. I was hoping to resize without having to copy the original to my server first (since the images are large and I'd like to resize dynamically), but can't figure out how. This is what I have so far (not much):

$container = $conn->get_container("originals"); 
$obj = $container->get_object("example.jpg"); 
$开发者_Go百科img = $obj->read();

Part of the problem is I don't fully understand what is being returned by the read() function. I know $img contains the object's "data" (which I was able to print out as gibberish), but it is neither a file nor a url nor an image resource, so I don't know how to deal with it. Is it possible to convert $img into an image resource somehow? I tried imagecreatefromjpeg($img) but that didn't work.

Thanks!


First, you cannot resize an image without loading it into memory. Unless the remote server offers some "resize my image for me, here are the parameters" API, you have to load the image in your script to manipulate it. So you'll have to copy the file from the CloudFiles container to your server, manipulate it, then send it back into storage.

The data you receive from $obj->read() is the image data. That is the file. It doesn't have a file name and it's not saved on the hard disk, but it is the entire file. To load this into gd to manipulate it, you can use imagecreatefromstring. That's analogous to using, for example, imagecreatefrompng, only that imagecreatefrompng wants to read a file from the file system by itself, while imagecreatefromstring just accepts the data that you have already loaded into memory.


You can try to dump the content of the $img variable into a writable file as per the below:

<?php
$filename = 'modifiedImage.jpg';

/* 
 * 'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate 
 * the file to zero length. If the file does not exist, attempt to create it. 
 */
$handle = fopen($filename, 'w+');

// Write $img to the opened\created file.
if (fwrite($handle, $img) === FALSE) {
    echo "Cannot write to file ($filename)";
    exit;
}

echo "Success, wrote to file ($filename)";

fclose($handle);
?>

More details:

http://www.php.net/manual/en/function.fopen.php

http://www.php.net/manual/en/function.fwrite.php

Edit:

You might also want to double check the type of data returned by the read() function, because if the data is not a jpg image, if it's for example a png, the extension of the file needs to be changed accordingly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜