Jump to content

Convert file field to image field during runtime


evanmcd
 Share

Recommended Posts

Hi all,

I have a situation in which a user can upload a file that's any one of a number of formats (pdf, mpg, jpg, etc.).  If the file is an image, I want to do some resizing.

However, when I call ->size(###,###) on the file field when an image is in it, I get an error.  Makes sense.  

I'm hoping there's an easy way to solve this without needing to create a separate field for image uploads.  

I tried following @Soma's advice from this thread, but kept getting an error from ImageSizer saying I was passing in invalid format.  I know the file in there is an image as it's getting displayed in the browser.

So, is there a standard way to convert a File field to an Image field?

Thanks.

Link to comment
Share on other sites

There's no thing as to change a file field to a image field on runtime just for if there's an image. There's no standard way as it's not meant to be used that way.

The only easy way would be to create a new Pageimage with the file. This requires an image field attached to the page in question so it can use that.

foreach($page->files as $f) {
    if($f->ext == 'jpg'){
        $image = new Pageimage($page->images, $f->filename);
        echo "<img src='{$image->size(100,0)->url}'/>";
    }
}
  • Like 6
Link to comment
Share on other sites

Good Morning,

Sorry for plain-text code. I'm on mobile. But could you do something with PHP's image detection functions to determine specific extensions?

I'm doing this quickly, just to get ideas across:

$finfo = new FileInfo(null, '$page->image->url');

// Get MIME of uploaded file

switch ($finfo->file($_FILES['image']['tmp_name'], FILEINFO_MIME) {

case 'image/jpg':

$image = imagecreatefromjpeg($_FILES['image']['tmp_name']);

break;

case 'image/png':

$image = imagecreatefrompng($_FILES['image']['tmp_name']);

break;

case 'image/gif':

$image = imagecreatefromgif($_FILES['image']['tmp_name']);

break;

}

Add whatever other file types there are, and then the code for what to do with them?

Thanks,

Matthew

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...