Symfony2, compress an image file - symfony

So, i have an action for upload an image on my server like :
if( ( $file = $request->files->get('file')) !== null) {
$date = new \DateTime();
$fileName = $this->getUser()->getId() . '_' . $date->getTimestamp();
$file->move('uploads', $fileName);
}
I need, just before move(), compress my image to reduce the size. Is there something for that with Symfony2 ?
How can i do that simply ?

Did you search on Google? https://github.com/liip/LiipImagineBundle does the trick!

Related

Create file dynamically as File object and then publish

It's evidently a little more complicated to create a file dynamically in SS4
$folder = Folder::find_or_make('Cards');
$filename = 'myimage.jpg';
$contents = file_get_contents('http://example.com/image.jpg');
$pathToFile = Controller::join_links(Director::baseFolder(), ASSETS_DIR, $folder->Title, $filename);
file_put_contents($pathToFile, $contents);
$image = Image::create();
$image->ParentID = $folder->ID;
$image->Title = "My title";
$image->Name = $filename;
$image->FileFilename = 'Cards/' . $filename;
$image->write();
Member::actAs(Member::get()->first(), function() use ($image, $folder) {
if (!$image->isPublished()) {
$image->publishFile();
$image->publishSingle();
}
if (!$folder->isPublished()) {
$folder->publishSingle();
}
});
The above, creates the file as expected in /assets/Cards/myimage.jpg and publishes it fine
However all previews are blank, so it's obviously not finding the file:
Any idea what I missed in creating the Image object?
This should work:
$folder = Folder::find_or_make('Cards');
$contents = file_get_contents('http://example.com/image.jpg');
$img = Image::create();
$img->setFromString($contents, 'image.jpg');
$img->ParentID = $parent->ID;
$img->write();
// This is needed to build the thumbnails
\SilverStripe\AssetAdmin\Controller\AssetAdmin::create()->generateThumbnails($img);
$img->publishSingle();
FYI: $img->Filename no longer exists. An Image or File object have a File property, which is a composite field of type DBFile. This composite fields contains the filename, hash and a variant…
So you should use the composite field to address these fields.

Download multiple images in zip in Wordpress

I am working on my personal wordpress site that distribute images.
In single post page, I registered several images via ACF(Advanced Custom Fields) and I know how to get image path/filename through get_field ACF function.
I just googled then found this page, but how can I apply this technique to wordpress site?
Download multiple images into zip
Now I am stuck...
On single post page, place the url of download_zip.php file, where you will place all your code for creating zip.
On single post page:
Download ZIP
In variable 'model_id', place the post id of the single post.
Now create a download_zip.php file on the root of your wordpress setup, where wp-config.php file exists.
Here is the code of download_zip.php file.
<?php
/*File for downloading the gallery zip files*/
$post_id = $_GET['model_id'];
require_once('wp-blog-header.php');
require_once('/wp-admin/includes/file.php');
WP_Filesystem();
$files_to_zip = array();
$zip = new ZipArchive();
$title = get_the_title($post_id);
$destination = wp_upload_dir();
//var_dump($destination);
$destination_path = $destination['basedir'];
$DelFilePath = str_replace(" ","_",$title).'_'.$post_id.'_'.time().'.zip' ;
$zip_destination_path = $destination_path."/".$DelFilePath;
if(file_exists($destination_path."/".$DelFilePath)) {
unlink ($destination_path."/".$DelFilePath);
}
if ($zip->open($destination_path."/".$DelFilePath, ZIPARCHIVE::CREATE) != TRUE) {
die ("Could not open archive");
}
//this is only for retrieving Repeater Image custom field
$row1 = get_field('acf_field_name1',$post_id);
$row1 = get_field('acf_field_name2',$post_id);
$rows = array($row1,$row2);
if($rows) {
foreach($rows as $row): ?>
<?php
$explode = end(explode("uploads",$row));
$index_file = array($destination_path,$explode);
$index_file = implode("",$index_file);
$new_index_file = basename($index_file);
$zip->addFile($index_file,$new_index_file);
endforeach;
}
$zip->close();
if(file_exists($zip_destination_path)) {
send_download($zip_destination_path);
}
//The function with example headers
function send_download($file) {
$basename = basename($file);
$length = sprintf("%u",filesize($file));
header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.$basename.'"');
header('Content-Transfer-Encoding: binary');
header('Pragma: public');
header('Content-Length: ' . $length);
set_time_limit(0);
ob_clean();
flush();
readfile($file); // "Outputs" the file.
unlink($file);
}
?>
Please modify this code according to your requirement such as get_field(), place your image field name inside it, & define your upload directory, so that you can break the url in $explode variable for defining path of image in $index_file variable.
And please also check your destination path stored in $destination_path variable is correct or not.
Hope, this may be helpful to you.

Creating a folder with PHP using input values

I am trying to create a folder in PHP, by calling a value. Creating one works fine. But once I try calling the value instead and concatenating it with the existing folder, it won't work. I have tried several things.
For example, I want to be able to have someone type in a name for their folder in an input field, so that they may choose what will the name of the folder be. For example, they could write on the website "mypics", and when I access my ftp program, I would now see images/mypics/
As for the HTML portion, I have this (check the fiddle for the rest of it http://jsfiddle.net/GF6qk/ ):
<input type="text" id="folder" name="folder">
As for the PHP aspect, I have the following
<?php
// We're putting all our files in a directory called images.
// Desired folder structure
$folder = $_POST['folder'];
$dirPath = 'images/'.$folder;
$result = mkdir($dirPath, 0755);
if ($result == 1) {
echo $dirPath . " has been created";
} else {
echo $dirPath . " has NOT been created";
}
//$image_name = '';
$uploaddir = 'images';
// The posted data, for reference
$file = $_POST['value'];
$name = $_POST['name'];
// Get the mime
$getMime = explode('.', $name);
$mime = end($getMime);
// Separate out the data
$data = explode(',', $file);
// Encode it correctly
$encodedData = str_replace(' ','+',$data[1]);
$decodedData = base64_decode($encodedData);
?>
I have also used this line (which was the original line I tried in the above code, which I then changed).
$dirPath = 'images/$folder';
try this and it is working
$folder = $_POST['folder'];
$dirPath = 'images/'.$folder;
$result = mkdir($dirPath);
if ($result == '1') {
echo $dirPath . " has been created";
} else {
echo $dirPath . " has NOT been created";
}
<input type="text" id="folder" name="folder">
Are you receiving any errors? If so, what are they? Does the "images" folder already exist? I tried your exact code, and it worked if the images folder already exists.....

Naming Drupal 7 template files based on url

If I have a page whose url alias is "/api/user/create", how can I name a template file based on the url such as "page-api-user-create.tpl.php".
You need to name it:
page--api--user--create.tpl.php
(note double dashes in the file name).
See http://drupal.org/node/1089656 for more info.
You can set up a page level template file to reflect the url, as was explained by Maciej Zgazdaj.
To do the same with a node level template file you have to add this to your template.php file:
function YOURTHEME_preprocess_node(&$variables) {
$url = str_replace("-", "", $variables['node_url']);
$urlParts = explode("/", $url);
unset($urlParts[0]);
if($urlParts[1] !== false) {
$out = array();
$sug = "node";
foreach($urlParts as $val) {
$sug .= "__".$val;
$out[] = $sug;
}
$variables['theme_hook_suggestions'] =
array_merge($variables['theme_hook_suggestions'], $out);
}
}
Replace YOURTHEME with .. well your theme. Check the offered suggestions with devel_themer.

Rename files during upload within Wordpress backend

is there a way to rename files during the upload progress within the Wordpress 3.0 backend? I would like to have a consistent naming of files, especially for images.
I think an 12 (+-) digit hash value of the original filename or something similar would be awesome. Any suggestions?
Regards
But it would really be easier to do that before uploading files.
Not quite sure about that - this seems fairly easy;
/**
* #link http://stackoverflow.com/a/3261107/247223
*/
function so_3261107_hash_filename( $filename ) {
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$name = basename( $filename, $ext );
return md5( $name ) . $ext;
}
add_filter( 'sanitize_file_name', 'so_3261107_hash_filename', 10 );
This filter creates a 32 character hash of the original filename, preserving the file extension. You could chop it down a little using substr() if you wanted to.
This filter runs once the file has been uploaded to a temporary directory on your server, but before it is resized (if applicable) and saved to your uploads folder.
Note that there is no risk of file overwrite - in the event that a newly hashed file is the same as one that already exists, WordPress will try appending an incrementing digit to the filename until there is no longer a collision.
WordPress Plugin
<?php
/**
* Plugin Name: Hash Upload Filename
* Plugin URI: http://stackoverflow.com/questions/3259696
* Description: Rename uploaded files as the hash of their original.
* Version: 0.1
*/
/**
* Filter {#see sanitize_file_name()} and return an MD5 hash.
*
* #param string $filename
* #return string
*/
function so_3261107_hash_filename( $filename ) {
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$name = basename( $filename, $ext );
return md5( $name ) . $ext;
}
add_filter( 'sanitize_file_name', 'so_3261107_hash_filename', 10 );
http://wpapi.com/change-image-name-to-wordpress-post-slug-during-upload/
BTW:
Add filter to sanitize_file_name is totally wrong, as sanitize_file_name() function is a helper function to format string, it may be used elsewhere like plugins or themes.
function wp_modify_uploaded_file_names($file) {
$info = pathinfo($file['name']);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$name = basename($file['name'], $ext);
$file['name'] = uniqid() . $ext; // uniqid method
// $file['name'] = md5($name) . $ext; // md5 method
// $file['name'] = base64_encode($name) . $ext; // base64 method
return $file;
}
add_filter('wp_handle_upload_prefilter', 'wp_modify_uploaded_file_names', 1, 1);
I've made a plugin for it. I did it because i was having too much trouble with my clients trying to upload images with special characters
http://wordpress.org/plugins/file-renaming-on-upload
I implemented the same thing, I wanted a more random filename, than the original, as the site I am using this for is for pics only and all files are in one directory.
i did the following
return md5($ip . uniqid(mt_rand(), true)) . $ext;
I was really looking for a plugin that could do it properly, and finally I ended up making this one myself. It's available on my blog: http://www.meow.fr/media-file-renamer ! If you use it, please give me a feedback :) I sincerely hope it helps!
You can't autorename file with the media library function. I would recommend to rename files before you upload them. Even after uploading a file you can't rename it throug WordPress but only through FTP.
The only way to do that would be a plugin that hooks itself into the media library upload process. But it would really be easier to do that before uploading files.

Resources