Save image in different formats - php

I have images I want to save in different formats based on user selection using GD. For PNG, JPG, and GIF images, there is a function to save the image in that format.
How can I save the image as TIFF, BMP, or PSD? Is any function available for those formats?

You cannot do that with GD, you need to use ImageMagick. I assume you have already image in a format png, and that image url is $imageUrl.;
$imageFormat = $_POST["format"];
$imageFormats = array("tiff", "bmp");
if (in_array($imageFormat, $imageFormats)) {
$handle = fopen($imageUrl, 'rb');
$imageMagick = new Imagick();
$imageMagick->readImageFile($handle);
$imageMagick->setImageFormat($imageFormat);
$imageMagick->setImageColorSpace(5);
$imageMagick->writeImage("path_to_tiff_image." . $imageFormat);
fclose($handle);
$imageMagick->destroy();
} else {
die("Invalid format!");
}
For PSD part, why do you want to save it as psd? There is no way to do that. If you say the reason of saving as psd, I can help you.

You can use inbuilt image type and mime type of GD library. Ex:
array (IMAGETYPE_PSD => 'psd', "mime_type" => 'image/psd'),
array (IMAGETYPE_BMP => 'bmp', "mime_type" => 'image/bmp'),
array (IMAGETYPE_TIFF_II => 'tiff', "mime_type" => 'image/tiff')

<?php
if(!function_exists('image_type_to_extension')){
$extension;
function image_type_or_mime_type_to_extension($image_type, $include_dot) {
define ("INVALID_IMAGETYPE", '');
$extension = INVALID_IMAGETYPE; /// Default return value for invalid input
$image_type_identifiers = array ( ### These values correspond to the IMAGETYPE constants
array (IMAGETYPE_GIF => 'gif', "mime_type" => 'image/gif'), ### 1 = GIF
array (IMAGETYPE_JPEG => 'jpg', "mime_type" => 'image/jpeg'), ### 2 = JPG
array (IMAGETYPE_PNG => 'png', "mime_type" => 'image/png'), ### 3 = PNG
array (IMAGETYPE_SWF => 'swf', "mime_type" => 'application/x-shockwave-flash'), ### 4 = SWF // A. Duplicated MIME type
array (IMAGETYPE_PSD => 'psd', "mime_type" => 'image/psd'), ### 5 = PSD
array (IMAGETYPE_BMP => 'bmp', "mime_type" => 'image/bmp'), ### 6 = BMP
array (IMAGETYPE_TIFF_II => 'tiff', "mime_type" => 'image/tiff'), ### 7 = TIFF (intel byte order)
array (IMAGETYPE_TIFF_MM => 'tiff', "mime_type" => 'image/tiff'), ### 8 = TIFF (motorola byte order)
array (IMAGETYPE_JPC => 'jpc', "mime_type" => 'application/octet-stream'), ### 9 = JPC // B. Duplicated MIME type
array (IMAGETYPE_JP2 => 'jp2', "mime_type" => 'image/jp2'), ### 10 = JP2
array (IMAGETYPE_JPX => 'jpf', "mime_type" => 'application/octet-stream'), ### 11 = JPX // B. Duplicated MIME type
array (IMAGETYPE_JB2 => 'jb2', "mime_type" => 'application/octet-stream'), ### 12 = JB2 // B. Duplicated MIME type
array (IMAGETYPE_SWC => 'swc', "mime_type" => 'application/x-shockwave-flash'), ### 13 = SWC // A. Duplicated MIME type
array (IMAGETYPE_IFF => 'aiff', "mime_type" => 'image/iff'), ### 14 = IFF
array (IMAGETYPE_WBMP => 'wbmp', "mime_type" => 'image/vnd.wap.wbmp'), ### 15 = WBMP
array (IMAGETYPE_XBM => 'xbm', "mime_type" => 'image/xbm') ### 16 = XBM
);
if((is_int($image_type)) AND (IMAGETYPE_GIF <= $image_type) AND (IMAGETYPE_XBM >= $image_type)){
$extension = $image_type_identifiers[$image_type-1]; // -1 because $image_type_identifiers array starts at [0]
$extension = $extension[$image_type];
}
elseif(is_string($image_type) AND (($image_type != 'application/x-shockwave-flash') OR ($image_type != 'application/octet-stream'))){
$extension = match_mime_type_to_extension($image_type, $image_type_identifiers);
}
else
{
$extension = INVALID_IMAGETYPE;
}
if(is_bool($include_dot)){
if((false != $include_dot) AND (INVALID_IMAGETYPE != $extension)){
$extension = '.' . $extension;
}
}
else
{
$extension = INVALID_IMAGETYPE;
}
return $extension;
}
}
function match_mime_type_to_extension($image_type, $image_type_identifiers){
// Return from loop on a match
foreach($image_type_identifiers as $_key_outer_loop => $_val_outer_loop){
foreach($_val_outer_loop as $_key => $_val){
if(is_int ($_key)){ // Keep record of extension for mime check
$extension = $_val;
}
if($_key == 'mime_type'){
if($_val === $image_type){ // Found match no need to continue looping
return $extension; ### Return
}
}
}
}
// Compared all values without match
return $extension = INVALID_IMAGETYPE;
}
$extension = image_type_or_mime_type_to_extension($image_type, $include_dot);
return $extension;
}
?>

Related

php readfile() and fopen() damaged/corrupt download

Long time lurker first time poster,
Im done pulling my hair out over this, so i figured i would swallow the pride and ask the experts,
I have read in excess of 20 similar issues here and tried all fixes solutions but im getting the same results.
Im using PHP for users to download items, however i have tried readfile and fopen but EVERY download is corrupt, sometimes 0 in size other times the correct(ish) size, But always damaged or corrupt
Can someone take a peek at this code and tell me whats wrong with it, ive scoured it so many times now im probably just missing something rediculously simple, ..... as usual
Any help would be greatly appreciated.
(contents of /loap.php can be shown if needed)
EDIT : Resolved
Just a quick update for anyone who stumbled across this, I managed to get this working ...... I had tried many different variations of certain commands, but it seems i had missed trying with "ob_clean()" and "ob_end_flush()" with fopen(),
.. It did the trick and as i expected it was a simple fix Thanks for the help Twisty, you poked at my inspiration ;)
<?php
require_once('../secura/load.php');
function get_remote_file_size($url, $readable = true){
$parsed = parse_url($url);
$host = $parsed["host"];
$fp = #fsockopen($host, 80, $errno, $errstr, 20);
if(!$fp) return false;
else {
#fputs($fp, "HEAD $url HTTP/1.1\r\n");
#fputs($fp, "HOST: $host\r\n");
#fputs($fp, "Connection: close\r\n\r\n");
$headers = "";
while(!#feof($fp))$headers .= #fgets ($fp, 128);
}
#fclose ($fp);
$return = false;
$arr_headers = explode("\n", $headers);
foreach($arr_headers as $header) {
$s = "Content-Length: ";
if(substr(strtolower ($header), 0, strlen($s)) == strtolower($s)) {
$return = trim(substr($header, strlen($s)));
break;
}
}
return $return;
}
function get_ext($name)
{
$fn = get_basename($name);
return (strpos($fn, '.') ? strtolower(substr(strrchr($fn, '.'), 1)) : '');
}
function get_basename($name)
{
return basename(str_replace('\\', '/', $name));
}
function get_filesize_unit($size)
{
$size = max(0, $size);
static $u = array(' B', 'KB', 'MB', 'GB');
for ($i=0; $size >= 1024 && $i < 4; $i++)
{
$size /= 1024;
}
return number_format($size, 1).' '.$u[$i];
}
///////////////////////////////////////////////////////////////////////////////////////////////
function find_mime_type($ext)
{
static $mime_types = array(
'application/andrew-inset' => array('ez'),
'application/mac-binhex40' => array('hqx'),
'application/mac-compactpro' => array('cpt'),
'application/mathml+xml' => array('mathml'),
'application/msword' => array('doc'),
'application/octet-stream' => array('bin', 'dms', 'lha',
'lzh', 'exe', 'class', 'so', 'dll', 'dmg'),
'application/oda' => array('oda'),
'application/ogg' => array('ogg'),
'application/pdf' => array('pdf'),
'application/postscript' => array('ai', 'eps', 'ps'),
'application/rdf+xml' => array('rdf'),
'application/smil' => array('smi', 'smil'),
'application/srgs' => array('gram'),
'application/srgs+xml' => array('grxml'),
'application/vnd.mif' => array('mif'),
'application/vnd.mozilla.xul+xml' => array('xul'),
'application/vnd.ms-excel' => array('xls'),
'application/vnd.ms-powerpoint' => array('ppt'),
'application/vnd.wap.wbxml' => array('wbxml'),
'application/vnd.wap.wmlc' => array('wmlc'),
'application/vnd.wap.wmlscriptc' => array('wmlsc'),
'application/voicexml+xml' => array('vxml'),
'application/x-bcpio' => array('bcpio'),
'application/x-cdlink' => array('vcd'),
'application/x-chess-pgn' => array('pgn'),
'application/x-cpio' => array('cpio'),
'application/x-csh' => array('csh'),
'application/x-director' => array('dcr', 'dir', 'dxr'),
'application/x-dvi' => array('dvi'),
'application/x-futuresplash' => array('spl'),
'application/x-gtar' => array('gtar'),
'application/x-hdf' => array('hdf'),
'application/x-javascript' => array('js'),
'application/x-koan' => array('skp', 'skd', 'skt', 'skm'),
'application/x-latex' => array('latex'),
'application/x-netcdf' => array('nc', 'cdf'),
'application/x-sh' => array('sh'),
'application/x-shar' => array('shar'),
'application/x-shockwave-flash' => array('swf'),
'application/x-stuffit' => array('sit'),
'application/x-sv4cpio' => array('sv4cpio'),
'application/x-sv4crc' => array('sv4crc'),
'application/x-tar' => array('tar'),
'application/x-tcl' => array('tcl'),
'application/x-tex' => array('tex'),
'application/x-texinfo' => array('texinfo', 'texi'),
'application/x-troff' => array('t', 'tr', 'roff'),
'application/x-troff-man' => array('man'),
'application/x-troff-me' => array('me'),
'application/x-troff-ms' => array('ms'),
'application/x-ustar' => array('ustar'),
'application/x-wais-source' => array('src'),
'application/xhtml+xml' => array('xhtml', 'xht'),
'application/xslt+xml' => array('xslt'),
'application/xml' => array('xml', 'xsl'),
'application/xml-dtd' => array('dtd'),
'application/zip' => array('zip'),
'audio/basic' => array('au', 'snd'),
'audio/midi' => array('mid', 'midi', 'kar'),
'audio/mpeg' => array('mpga', 'mp2', 'mp3'),
'audio/x-aiff' => array('aif', 'aiff', 'aifc'),
'audio/x-mpegurl' => array('m3u'),
'audio/x-pn-realaudio' => array('ram', 'ra'),
'application/vnd.rn-realmedia' => array('rm'),
'audio/x-wav' => array('wav'),
'chemical/x-pdb' => array('pdb'),
'chemical/x-xyz' => array('xyz'),
'image/bmp' => array('bmp'),
'image/cgm' => array('cgm'),
'image/gif' => array('gif'),
'image/ief' => array('ief'),
'image/jpeg' => array('jpeg', 'jpg', 'jpe'),
'image/png' => array('png'),
'image/svg+xml' => array('svg'),
'image/tiff' => array('tiff', 'tif'),
'image/vnd.djvu' => array('djvu', 'djv'),
'image/vnd.wap.wbmp' => array('wbmp'),
'image/x-cmu-raster' => array('ras'),
'image/x-icon' => array('ico'),
'image/x-portable-anymap' => array('pnm'),
'image/x-portable-bitmap' => array('pbm'),
'image/x-portable-graymap' => array('pgm'),
'image/x-portable-pixmap' => array('ppm'),
'image/x-rgb' => array('rgb'),
'image/x-xbitmap' => array('xbm'),
'image/x-xpixmap' => array('xpm'),
'image/x-xwindowdump' => array('xwd'),
'model/iges' => array('igs', 'iges'),
'model/mesh' => array('msh', 'mesh', 'silo'),
'model/vrml' => array('wrl', 'vrml'),
'text/calendar' => array('ics', 'ifb'),
'text/css' => array('css'),
'text/html' => array('html', 'htm'),
'text/plain' => array('asc', 'txt'),
'text/richtext' => array('rtx'),
'text/rtf' => array('rtf'),
'text/sgml' => array('sgml', 'sgm'),
'text/tab-separated-values' => array('tsv'),
'text/vnd.wap.wml' => array('wml'),
'text/vnd.wap.wmlscript' => array('wmls'),
'text/x-setext' => array('etx'),
'video/mpeg' => array('mpeg','3gp','mp4', 'mpg', 'mpe'),
'video/quicktime' => array('qt', 'mov'),
'video/vnd.mpegurl' => array('mxu', 'm4u'),
'video/x-msvideo' => array('avi'),
'video/x-sgi-movie' => array('movie'),
'x-conference/x-cooltalk' => array('ice')
);
foreach ($mime_types as $mime_type => $exts)
{
if (in_array($ext, $exts))
{
return $mime_type;
}
}
return 'text/plain';
}
$id = $_GET['id'];
$error = false;
$error = (!$product->is_product($id)?$products->error:$error);
$error =(!$purchases->is_purchased($_SESSION['uid'],$id)?$purchases->error:$error);
if(!$error){
$file = $product->details($id);
$filepath = $file['file'];
$fname=get_basename($filepath);
if (fopen($filepath,r) || (file_exists($filepath)) ){
if (#filesize($filepath)){
$fsize =filesize($filepath);
}
else
{
$fsize = get_remote_file_size($filepath);
}
$ext= get_ext($fname);
$ctype= find_mime_type($ext);
header('Content-Type:'. $ctype );
header('Content-Length: ' . $fsize);
header('Content-Disposition: attachment; filename=' . $fname);
ob_clean();
$file = fopen($filepath,'r');
ob_end_flush();
fpassthru($file);
set_time_limit(0);
}else{
return 'File Doesn\'t Exist'; } // exist fxn....
}
echo $error;
?>
Just a quick update for anyone who stumbled across this, I managed to get this working ......
I had tried many different variations of certain commands,
but it seems i had missed trying with ob_clean() and ob_end_flush() with fopen() , ..
It did the trick and as i expected it was a simple fix
Thanks for the help Twisty, you poked at my inspiration ;)
The corrected and working code has been updated in the OP
Make sure you do not have any code executed after the last line readfile(FILE_NAME)
In my case, I had to add die(); or exit(); as the last line, because MVC framework continues to render the view after readfile

REST CODEIGNITER multiple upload file

i'm try to build REST API use codeigniter plugin from https://github.com/chriskacerguis/codeigniter-restserver
i'm successfull built multiple upload with this, but i have a trouble when upload many file data.
when i'm select 3 file in my directory, my code work, but in upload path i just have 2 file.
here controller :
function upload_post()
{
$name_array = array();
$count = count($_FILES['userfile']['size']);
foreach($_FILES as $key=>$value)
{
for($s=0; $s<=$count-1; ) {
$_FILES['userfile']['name']=$value['name'][$s];
$_FILES['userfile']['type'] = $value['type'][$s];
$_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['userfile']['error'] = $value['error'][$s];
$_FILES['userfile']['size'] = $value['size'][$s];
$config['upload_path'] = 'E:/tes/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$name_array[] = $data['file_name'];
$s++;
}
}
$names= implode(',', $name_array);
/* $this->load->database();
$db_data = array('id'=> NULL,
'name'=> $names);
$this->db->insert('testtable',$db_data);
*/ print_r($names);
print_r($count);
}
I have made a helper function for me which upload the files and return a array with upload result.It takes a parameter upload directory where to save the files. Here is the my function
function upload_file($save_dir="images")//takes folder name where to save.default images folder
{
$CI = & get_instance();
$CI->load->library('upload');
$config=array();
$config['upload_path'] = FCPATH.$save_dir;
$config['allowed_types'] = 'gif|jpg|png';//only images.you can set more
$config['max_size'] = 1024*10;//10 mb you can increase more.Make sure your php.ini has congifured same or more value like this
$config['overwrite'] = false;//if file do not replace.create new file
$config['remove_spaces'] = true;//remove sapces from file
//you can set more config like height width for images
$uploaded_files=array();
foreach ($_FILES as $key => $value)
{
if(strlen($value['name'])>0)
{
$CI->upload->initialize($config);
if (!$CI->upload->do_upload($key))
{
$uploaded_files[$key]=array("status"=>false,"message"=>$value['name'].': '.$CI->upload->display_errors());
}
else
{
$uploaded_files[$key]=array("status"=>true,"info"=>$CI->upload->data());
}
}
}
return $uploaded_files;
}
Sample output
if you print out the function returns you will get the output like this
Array
(
[file_input_name1] => Array
(
[status] => 1//status will be true if uploaded
[info] => Array //if success it will return the file informattion
(
[file_name] => newfilename.jpg
[file_type] => image/jpeg
[file_path] => C:/Program Files (x86)/VertrigoServ/www/rnd/images/
[full_path] => C:/Program Files (x86)/VertrigoServ/www/rnd/images/newfilename.jpg
[raw_name] => newfilename
[orig_name] => newfilename.jpg
[client_name] => newfilename
[file_ext] => .jpg
[file_size] => 762.53
[is_image] => 1
[image_width] => 1024
[image_height] => 768
[image_type] => jpeg
[image_size_str] => width="1024" height="768"
)
)
[file_input_name_2] => Array
(
[status] =>//if invalid file status will be false with error message
[message] => desktop.ini: <p>The filetype you are attempting to upload is not allowed.</p>
)
)
Hope it may help you

PHP File Upload Restrictions

I want to put a restriction on the size of images uploaded.
Below I have condition for image size.
if ($_FILES["upload_attachment"]["size"] < 25000)) // Max File Size: 25KB
{
echo "File size exceeds maximum.";
}
I want insert condition in this code.
if ( $_FILES ) {
$files = $_FILES['upload_attachment'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("upload_attachment" => $file);
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$post->ID);
}
}
}
}
Basically, you want to check that early, before you proceed with file processing, so you're not making the server do any work if it doesn't have to.
Also, FYI, the upload size is specified in bytes, so if you want 25KB, it will be (25 * 1024) = 25600 bytes.
To incorporate that condition, you could do this. It gets a little gnarly, so I've added comments on the closing brackets to note which closes what. fe = foreach
if ( $_FILES ) {//if files exist
if ($_FILES["upload_attachment"]["size"] < 25600) { // Max File Size: 25KB
//I would also recommend adding error handling early.
if ($_FILES['filename']['error'] > 0){
echo 'Error: ' . $_FILES['filename']['error'] . '<br />';
} else {
$files = $_FILES['upload_attachment'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("upload_attachment" => $file);
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$post->ID);
}//fe
}//if
}//fe
}//if no errors (else)
} //if size ok
else {
echo "File size exceeds maximum.";
}
}//if $_FILES

Codeigniter 2.1 - fileupload You did not select a file to upload

Model function:
public function file_upload($folder, $allowed_type, $max_size = 0, $max_width = 0, $max_height = 0)
{
$folder = $this->path . $folder;
$files = array();
$count = 0;
foreach ($_FILES as $key => $value) :
$file_name = is_array($value['name']) ? $value['name'][$count] : $value['name'];
$file_name = $this->global_functions->char_replace($file_name, '_');
$count++;
$config = array(
'allowed_types' => $allowed_type,
'upload_path' => $folder,
'file_name' => $file_name,
'max_size' => $max_size,
'max_width' => $max_width,
'max_height' => $max_height,
'remove_spaces' => TRUE
);
$this->load->library('image_lib');
$this->image_lib->clear();
$this->load->library('upload');
$this->upload->initialize($config);
if (!$this->upload->do_upload($key)) :
$error = array('error' => $this->upload->display_errors());
var_dump($error);
return FALSE;
else :
$file = $this->upload->data();
$files[] = $file['file_name'];
endif;
endforeach;
if(empty($files)):
return FALSE;
else:
return implode(',', $files);
endif;
}
This function is working partially. Files are being uploaded to the selected folder, but I am getting this error: You did not select a file to upload. and getting FALSE as a result? What seems to be a problem? (form is using form_open_multipart)
Please make sure that you have this name of your file tag field:
$key='userfile' //which is name of input type field name
Are any of your file inputs empty when this happens? $_FILES will contain an array of "empty" data if there is no file specified for the input. For example, my file input name is one, and I submitted it without specifying a file:
Array
(
[one] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] => 0
)
)
You should check if the file data is empty before processing the upload. PHP's is_uploaded_file() is useful for this.

PHP: filename without file extension- best way?

I am trying to pull the filename out of a directory without the extension.
I am kludging my way through with the following:
foreach ($allowed_files as $filename) {
$link_filename = substr(basename($filename), 4, strrpos(basename($filename), '.'));
$src_filename = substr($link_filename, 0, strrpos($link_filename) - 4);
echo $src_filename;
}
...But that can't work if the extension string length is more than 3.
I looked around in the PHP docs to no avail.
PHP has a handy pathinfo() function that does the legwork for you here:
foreach ($allowed_files as $filename) {
echo pathinfo($filename, PATHINFO_FILENAME);
}
Example:
$files = array(
'somefile.txt',
'anotherfile.pdf',
'/with/path/hello.properties',
);
foreach ($files as $file) {
$name = pathinfo($file, PATHINFO_FILENAME);
echo "$file => $name\n";
}
Output:
somefile.txt => somefile
anotherfile.pdf => anotherfile
/with/path/hello.properties => hello
try this
function file_extension($filename){
$x = explode('.', $filename);
$ext=end($x);
$filenameSansExt=str_replace('.'.$ext,"",$filename);
return array(
"filename"=>$filenameSansExt,
"extension"=>'.'.$ext,
"extension_undotted"=>$ext
);
}
usage:
$filenames=array("file1.php","file2.inc.php","file3..qwe.e-rt.jpg");
foreach($filenames as $filename){
print_r(file_extension($filename));
echo "\n------\n";
}
output
Array
(
[filename] => file1
[extension] => .php
[extension_undotted] => php
)
------
Array
(
[filename] => file2.inc
[extension] => .php
[extension_undotted] => php
)
------
Array
(
[filename] => file3..qwe.e-rt
[extension] => .jpg
[extension_undotted] => jpg
)
------
list($file) = explode('.', $filename);
Try this:
$noExt = preg_replace("/\\.[^.]*$/", "", $filename);
Edit in response to cletus's comment:
You could change it in one of a few ways:
$noExt = preg_replace("/\\.[^.]*$/", "", basename($filename));
// or
$noExt = preg_replace("/\\.[^.\\\\\\/]*$/", "", $filename);
Yes, PHP needs regex literals...

Categories