I am generating a gif barcode using Pear Barcode2.
this currently works and I can see the image as gif image file. so the page is not shown in HTML form but as a stand alone image.
my code is:
$small_graph_height = 55;
$small_graph_width = 1.2;
$large_graph_height = 55;
$large_graph_width = 1.14;
$type = "gif";
$code = "code39";
$to_browser = TRUE;
include_once "application/libraries/Image/Barcode2.php";
$ticketno='TDN4993';
$productserial_str = empty($productserial_str) ? ucfirst($ticketno) : $productserial_str;
$productserial_type = $code;
$productserial_imgtype = $type;
$productserial_bSendToBrowser = $to_browser;
$productserial_height = $large_graph_height;
$productserial_width = $large_graph_width;
$productserial_img = Image_Barcode2::draw($productserial_str, $productserial_type, $productserial_imgtype, $productserial_bSendToBrowser, $productserial_height, $productserial_width);
ob_start();
imagepng($productserial_img);
$productserial_imgBase64 = base64_encode(ob_get_contents());
ob_end_clean();
imagedestroy($productserial_img);
$image= '<img class="ProductSerial" src="data:image/' . $productserial_imgtype . ';base64,' . $productserial_imgBase64 . '">';
echo $image;
what I want to do is save this image directly to the server hard disk rather than display it to the user.
I have tried to use PHP's imagegif but it doesnt like the fact that $image is in a string format.
Any advice will be welcome. Thanks as always
If you need to save the image on the disk you would need to use imgpng() function.
An example which i got from here.
imagepng($bc->draw($data, $type, 'png', false),'ur_image_location');
$small_graph_height = 55;
$small_graph_width = 1.2;
$large_graph_height = 55;
$large_graph_width = 1.14;
$type = "gif";
$code = "code39";
$to_browser = TRUE;
include_once "application/libraries/Image/Barcode2.php";
$ticketno='TDN4993';
$productserial_str = empty($productserial_str) ? ucfirst($ticketno) : $productserial_str;
$productserial_type = $code;
$productserial_imgtype = $type;
$productserial_bSendToBrowser = $to_browser;
$productserial_height = $large_graph_height;
$productserial_width = $large_graph_width;
$productserial_img = Image_Barcode2::draw($productserial_str, $productserial_type, $productserial_imgtype, $productserial_bSendToBrowser, $productserial_height, $productserial_width);
ob_start();
imagepng($productserial_img);
$png = ob_get_contents();
ob_end_clean();
file_put_contents('barcode.png', $png);
echo 'image saved to file barcode.png';
Related
I am trying to upload an image from my android application to a php script on my server. In my script, I am attempting to decode the image (using base64_decode) and then use file_put_contents() to save the image as a file in my directory. My problem is that the file 'appears' empty when I have .jpg at the end of the file name. When I removed that to see what was added for the image encoding, I see a very long string of characters, (65214 bytes specifically that were written to the file). When I run the code again, only this time uploading the $_POST['sent_image'] without decoding, I get the same exact string of text.
I am not sure what I am doing wrong... The end goal would be to save the image on the server, so it could be viewed elsewhere online, and also be able to retrieve it and get back into another activity in my android application.
All suggestions are appreciated!
NOTE: I have also tried imagecreatefromstring(), but that causes 0 bytes to be written.
My Code:PHP that gets encoded android image and tries to save to server directory:
<?php
include('inc.php');
if ((isset($_POST['searchinput'])) && (isset($_POST['newUnitStatus'])) && (isset($_POST['generalCause'])) && (isset($_POST['newUnitStatusComment'])) && (isset($_POST['newUnitStatusPhoto'])) && (isset($_POST['lexauser'])) && (isset($_POST['password']))) {
$sgref = "";
$searchinput = $_POST['searchinput'];
$newUnitStatus = $_POST['newUnitStatus'];
$generalCause = $_POST['generalCause'];
$newUnitStatusComment = $_POST['newUnitStatusComment'];
$lexauser = $_POST['lexauser'];
$pass = $_POST['password'];
if ((strpos($searchinput, "/") !== false)) {
$barcodesplit = preg_split('/\D/im', $searchinput, 4);
$sgref = $barcodesplit[0];
$lineitem = $barcodesplit[1];
$unitnumber = $barcodesplit[2];
$totalunits = $barcodesplit[3];
$unitname = $sgref."-".$lineitem."-".$unitnumber."_of_".$totalunits;
$photo = $_POST['newUnitStatusPhoto'];
$decodedPhoto = str_replace('data:image/jpg;base64,', '', $photo);
$decodedPhoto = str_replace(' ', '+', $decodedPhoto);
$newUnitStatusPhoto = base64_decode($decodedPhoto);
//$newUnitStatusPhoto = imagecreatefromstring($decodedPhoto);
$fileName = "".$unitname."_rej";
$target = '../LEXA/modules/bms/uploads/';
$newFile = $target.$fileName;
$docType = "Reject";
$success = file_put_contents($newFile, $newUnitStatusPhoto);
if($success === false) {
$response['message'] = "Couldn not write file.";
echo json_encode($response);
} else {
$response['message'] = "Wrote $success bytes. ";
echo json_encode($response);
}
} else {
$sgref = $searchinput;
$response['message'] = "I'm sorry, but you must enter a unit's uniqueid value to add a unit exception. Please view the siblings for this SG and pick the unit you need. Then you can add the new status.";
echo json_encode($response);
}
} else {
$response['message'] = "Your search value did not get sent. Please try again.";
echo json_encode($response);
}//End logic for post values.
?>
Thank you!
Using str_replace may be problematic if image format is other than jpg, for example.
Example code:
<?php
$photo = $_POST['newUnitStatusPhoto'];
if(substr($photo, 0,5) !== "data:"){
//do error treatment as it's not datauri
die("Error: no data: scheme");
};
$decodedPhoto = substr($photo, 5);
$mimeTerminator = stripos($decodedPhoto,";");
if($mimeTerminator === false){
die("Error: no mimetype found");
};
$decodedPhoto = substr($decodedPhoto, $mimeTerminator+8); //1<;>+4<base>+2<64>+1<,>
// $decodedPhoto = str_replace('data:image/jpg;base64,', '', $photo);
// $decodedPhoto = str_replace(' ', '+', $decodedPhoto);
$newUnitStatusPhoto = base64_decode($decodedPhoto);
//$newUnitStatusPhoto = imagecreatefromstring($decodedPhoto);
$unitname = "testando";
$fileName = "".$unitname."_rej.jpg";
$target = 'img/';
$newFile = $target.$fileName;
if(file_exists($newFile))
unlink($newFile);
$success = file_put_contents($newFile, $newUnitStatusPhoto);
echo $success;
My website lets logged users to use CKeditor and CKFinder to create pages or blog and of course upload image from editor. I got problem for many users that will use the same images in a single folder. I have searching for the same problem on StackOverflow and I found this question:
KCFinder with CKEditor - setting up dynamic folders for upload files.
I think the solution was good, but rather than creating many folders, I am just thinking how to save every user images by using a prefix of their user ID. For example the user with ID 10 will save his images with prefix 10_xxxxx.jpg and so on.
How to do it. Any body could show me where part of the file script that could be modified? I am using KCFinder V.3.12. Sorry for my English.
$_SESSION['id'] = 10;
public function upload() {
$config = &$this->config;
$file = &$this->file;
$url = $message = "";
if ($config['disabled'] || !$config['access']['files']['upload']) {
if (isset($file['tmp_name'])) #unlink($file['tmp_name']);
$message = $this->label("You don't have permissions to upload files.");
} elseif (true === ($message = $this->checkUploadedFile())) {
$message = "";
$dir = "{$this->typeDir}/";
if (isset($_GET['dir']) &&
(false !== ($gdir = $this->checkInputDir($_GET['dir'])))
) {
$udir = path::normalize("$dir$gdir");
if (substr($udir, 0, strlen($dir)) !== $dir)
$message = $this->label("Unknown error.");
else {
$l = strlen($dir);
$dir = "$udir/";
$udir = substr($udir, $l);
}
}
if (!strlen($message)) {
if (!is_dir(path::normalize($dir)))
#mkdir(path::normalize($dir), $this->config['dirPerms'], true);
$filename = $this->normalizeFilename($file['name']);
$target = file::getInexistantFilename($dir . $filename);
if (!#move_uploaded_file($file['tmp_name'], $target) &&
!#rename($file['tmp_name'], $target) &&
!#copy($file['tmp_name'], $target)
)
$message = $this->label("Cannot move uploaded file to target folder.");
else {
if (function_exists('chmod'))
#chmod($target, $this->config['filePerms']);
$this->makeThumb($target);
$url = $this->typeURL;
if (isset($udir)) $url .= "/$udir";
$url .= "/" . basename($target);
if (preg_match('/^([a-z]+)\:\/\/([^\/^\:]+)(\:(\d+))?\/(.+)$/', $url, $patt)) {
list($unused, $protocol, $domain, $unused, $port, $path) = $patt;
$base = "$protocol://$domain" . (strlen($port) ? ":$port" : "") . "/";
$url = $base . path::urlPathEncode($path);
} else
$url = path::urlPathEncode($url);
}
}
}
I'm trying to get the meta data out from my mp3 playlist using PHP and the library getid3, I'm sure the file path is correct and the mp3 has some information on meta data, but the information returns me null.
Here is my code :
<?php
header("Content-type: application/json");
require_once('getid3/getid3.php');
$input = json_decode(file_get_contents("php://input"), true);
$action = $input['action'];
switch ($action)
{
case "get_songs":
$currentDirectory = dirname(dirname(getcwd()));
$directory = $currentDirectory."/resources/assets/playlists/";
$files = glob($directory."*.mp3");
for($i = 0; $i < count($files); $i++)
{
$getID3 = new getID3;
$file = ($files[$i]);
$ThisFileInfo = $getID3->analyze($file);
$Result = array('song_url'=>($files[$i]), "tags"=> $ThisFileInfo);
$data[] = $Result;
}
$result = array("result"=>"ok","data"=>$data);
break;
}
echo json_encode($result);
?>
I know the library is working, because when I force it to access a local file it returns me :
"GETID3_VERSION" = "1.7.4";
error = (
"Could not open file \"AYO.mp3\""
);
Could it be, I cant access files from another path?
I have this database that contains images as strings. Those strings look something like this:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...
I need to create a link that will display this image. Like something.com/?id=27 is an image. All the images are in jpeg format. Here's what I've tried but didn't work:
<?php
$host = "smth";
$user = "smth";
$pass = "smth";
$db_name = "smth";
$dbh = new PDO("mysql:host=$host;dbname=$db_name", $user, $pass);
$dbh->exec("SET NAMES utf8");
$q = $dbh->prepare("select content from img where id = :id");
$q->execute(array(':id'=>$_GET['id']));
$row = $q->fetch(PDO::FETCH_BOTH);
header("Content-type: image/jpeg");
echo $row['content'];
?>
The data is being fetched correctly but the image is not displayed.
I need to be able to use this link like this <img src="mysite.com?id=21" /> and I do NOT want this solution: <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABA..." />
Thanks!
The solution to your problem is here:
How to decode a base64 string (gif) into image in PHP / HTML
Quoting that source but modifying:
In the case you strip out the first case and choose to decode the string, you should add this before echoing the decoded image data:
header("Content-type: image/gif");
$data = "/9j/4AAQSkZJRgABAQEAYABgAAD........";
echo base64_decode($data);
In the second case, use this instead:
echo '<img src="data:image/gif;base64,' . $data . '" />';
The second case is bad because the browser does not perform caching if the same image is shown on multiple pages.
Use this:
$code_base64 = $row['content'];
$code_base64 = str_replace('data:image/jpeg;base64,','',$code_base64);
$code_binary = base64_decode($code_base64);
$image= imagecreatefromstring($code_binary);
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
try this
//your image data
$logodata = "/9j/4AAQSkZJRgABAQEAYABgAAD........";
echo '<img src="data:image/gif;base64,' . $logodata . '" />';
Try this:
echo '<img src="data:image/png;base64,' . $base64encodedString . '" />
/**
* #param $base64_image_content
* #param $path
* #return bool|string
*/
function base64_image_content($base64_image_content,$path){
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
$type = $result[2];
$new_file = $path."/".date('Ymd',time())."/";
$basePutUrl = C('UPLOAD_IMG_BASE64_URL').$new_file;
if(!file_exists($basePutUrl)){
//Check if there is a folder, if not, create it and grant the highest authority.
mkdir($basePutUrl, 0700);
}
$ping_url = genRandomString(8).time().".{$type}";
$ftp_image_upload_url = $new_file.$ping_url;
$local_file_url = $basePutUrl.$ping_url;
if (file_put_contents($local_file_url, base64_decode(str_replace($result[1], '', $base64_image_content)))){
ftp_upload(C('REMOTE_ROOT').$ftp_image_upload_url,$local_file_url);
return $ftp_image_upload_url;
}else{
return false;
}
}else{
return false;
}
}
If you are dealing with data stored in a PostgreSQL database bytea field you will receive a stream when fetching the PDO. To process the data any further first transform the stream to usual data like this: $stream = $row['content']; rewind($stream); $data=stream_get_contents($stream);
I'm trying to create nodes programatically. Using Media module with the youtube extension, I'd like to populate a field with youtube data. From what I've read so far, it's going to look something like this:
<?php
// $value in this case is the youtube ID.
$file = new stdClass();
$file->uid = 1;
$file->filename = $value;
$file->uri = 'youtube://v/' . $value;
$file->filemime = 'video/youtube';
$file->type = 'video';
$file->status = 1;
$youtube = file_save($file);
node->field_youtube[$node->language]['0']['fid'] = (array) $youtube->fid;
?>
I learned this by looking at the information in the $content variable in the bartik theme. However, this results in a "Bad file extension" error. I also tried putting the whole url in $file->uri and using file_get_mimetype on it, then it didn't throw an error but the video didn't work either. Does anyone know how to do this?
I found the answer. The function file_save only checks if a file id is already in the database. However, the youtube uri field did not allow duplicates. Therefore I stole this function from the file_example module. It checks if a file exists with that uri, if it does it loads the object.
function file_example_get_managed_file($uri) {
$fid = db_query('SELECT fid FROM {file_managed} WHERE uri = :uri', array(':uri' => $uri))->fetchField();
if (!empty($fid)) {
$file_object = file_load($fid);
return $file_object;
}
return FALSE;
}
So in the end I simply put an if statement, like this:
$file_exists = wthm_get_managed_file('youtube://v/' . $value);
if (!$file_exists) {
$file_path = drupal_realpath('youtube://v/' . $value);
$file = new stdClass();
$file->uid = 1;
$file->filename = $value;
$file->uri = 'youtube://v/' . $value;
$file->filemime = file_get_mimetype($file_path);
$file->type = 'video';
$file->status = 1;
$file_exists = file_save($file);
}
$node->field_youtube[$node->language]['0'] = (array) $file_exists;
This solved most problems. I still get a message saying bad file extension, but it works anyway.
I got it working like this. I'm importing embed codes that need to be parsed and some are dupes, and i think this function file_uri_to_object($code, $use_existing = TRUE) allows you to reuse managed urls.
$r->video is an iframe embed code for youtube which gets parsed to the correct uri format
// include the media youtube handler.inc file to use the embed code parsing
$path = drupal_get_path('module','media_youtube').'/includes/MediaInternetYouTubeHandler.inc';
require_once($path);
$code = MediaInternetYouTubeHandler::parse($r->video);
$youtube = file_uri_to_object($code, $use_existing = TRUE);
$youtube->display = 1;
$youtube = file_save($youtube);
$node->field_video[$lang][0] = (array)$youtube;
node_save($node);
A nicer way:
module_load_include('inc', 'media_youtube', 'includes/MediaInternetYouTubeHandler.inc');
$obj = new MediaInternetYouTubeHandler($url);
$file = $obj->getFileObject();
$file->display = 1;
file_save($file);
$product->field_product_video[LANGUAGE_NONE][] = (array) $file;