I have a variable containing image which is returned from imagecopyresampled function, I want to convert this variable into base64 encoded format to return to my JavaScript file.
Error is that base64_encode and exif_imagetype funcions do not take image as input.
Here is my code:
<?php
$img_name = $_POST['name'];
$data = file_get_contents($img_name);
$crop_start_x = $_POST['crop_start_x'];
$crop_start_y = $_POST['crop_start_y'];
$crop_width = $_POST['crop_width'];
$crop_height = $_POST['crop_height'];
$dst_x = 0;
$dst_y = 0;
$src_x = $crop_start_x;
$src_y = $crop_start_y;
$dst_w = $crop_width;
$dst_h = $crop_height;
$src_w = $src_x + $dst_w;
$src_h = $src_y + $dst_h;
$dst_image = imagecreatetruecolor($dst_w, $dst_h);
$src_image = imagecreatefromstring($data);
imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
$type = exif_imagetype($dst_image);
$base64_image = 'data:image/' . $type . ';base64,' . base64_encode($dst_image);
echo $base64_image;
?>
This will work
$image = 'folder/your_image.png';
$type = pathinfo($image, PATHINFO_EXTENSION);
$imgdata = file_get_contents($image);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($imgdata);
for imagecopyresampled
imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
ob_start();
imagejpeg($dst_image, null);
$img = ob_get_clean();
$base64 = base64_encode($img)
Related
I have a code that can get the Amazon product price if you gave it's "ASIN" (It's Amazon product identification number)... below you can find the code (I don't think there is a need to read the code anyway).
<?php
class AmazonAPI {
var $amazon_aff_id;
var $amazon_access_key;
var $amazon_secret_key;
var $url_params;
var $itemID;
var $xml;
var $operation;
var $signature;
var $response_groups = "Small,Images,OfferSummary";
var $error_message;
var $error=0;
public function __construct($affid, $access, $secret)
{
$this->amazon_aff_id = $affid;
$this->amazon_access_key = $access;
$this->amazon_secret_key = $secret;
}
public function build_url()
{
$url = "http://webservices.amazon.com/onca/xml?";
$this->response_groups = str_replace(",", "%2C", $this->response_groups);
$url_params = "AWSAccessKeyId=" . $this->amazon_access_key;
$url_params .= "&AssociateTag=" . $this->amazon_aff_id;
if(!empty($this->itemID)) {
$url_params .= "&ItemId=" . $this->itemID;
}
$url_params .= "&Operation=" . $this->operation;
$url_params .= "&ResponseGroup=" . $this->response_groups;
$url_params .= "&Service=AWSECommerceService";
$url_params .= "&Timestamp=" . rawurlencode(gmdate("Y-m-d\TH:i:s\Z"));
$url_params .= "&Version=2013-08-01";
$this->url_params = $url_params;
$url .= $url_params;
$url .= "&Signature=" . $this->generate_signature();
return $url;
}
public function generate_signature()
{
$this->signature = base64_encode(hash_hmac("sha256",
"GET\nwebservices.amazon.com\n/onca/xml\n" . $this->url_params,
$this->amazon_secret_key, True));
$this->signature = str_replace("+", "%2B", $this->signature);
$this->signature = str_replace("=", "%3D", $this->signature);
return $this->signature;
}
public function item_lookup($id)
{
$this->operation = "ItemLookup";
$this->itemID = $id;
$url = $this->build_url();
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$output = curl_exec($ch);
curl_close($ch);
$this->xml = simplexml_load_string($output);
return $this;
}
public function check_for_errors()
{
if(isset($this->xml->Error)) {
$this->error_message = $this->xml->Error->Message;
$this->error = 1;
}
if(isset($this->xml->Items->Request->Errors)) {
$this->error_message = $this->xml->Items->Request->Errors->Error->Message;
$this->error = 1;
}
return $this->error;
}
public function get_item_price($product)
{
$price = 0;
if(isset($product->LowestNewPrice)) {
$price = $product->LowestNewPrice->Amount;
} elseif(isset($product->LowestUsedPrice)) {
$price = $product->LowestUsedPrice->Amount;
} elseif(isset($product->LowestCollectiblePrice)) {
$price = $product->LowestCollectiblePrice->Amount;
} elseif(isset($product->LowestRefurbishedPrice)) {
$price = $product->LowestRefurbishedPrice->Amount;
}
return $price;
}
public function get_item_data()
{
if($this->check_for_errors()) return null;
$product = $this->xml->Items->Item;
$item = new STDclass;
$item->detailedPageURL = $product->DetailPageURL;
$item->link = "https://www.amazon.com/gp/product/".$this->itemID."/?tag=" . $this->amazon_aff_id;
$item->title = $product->ItemAttributes->Title;
$item->smallImage = $product->SmallImage->URL;
$item->mediumImage = $product->MediumImage->URL;
$item->largeImage = $product->LargeImage->URL;
$item->price = $this->get_item_price($product->OfferSummary);
return $item;
}
}
?>
Then i echo the price with this code
$amazon = new AmazonAPI("associate-id", "access-key", "secret-key");
$item = $amazon->item_lookup("ASIN")->get_item_data();
echo $item->price;
Now if i have a csv sheet like this
https://ibb.co/dHS4EK
can i update the prices on column D and E given the asin found on column B and C,
so for example the value of cell D2 will get it using the following code
$amazon = new AmazonAPI("associate-id", "access-key", "secret-key");
$item = $amazon->item_lookup(Value on cell D2)->get_item_data();
echo $item->price;
then save the csv file after updating it's prices, is there a simple easy way to do that in maybe php especially that i'm very new to coding?
Edit 1: I need the csv file to import it using WooCommerce import tool which only accept csv files
Thanks in advance
What you have to do is:
Parse the CSV file into an array. You can use PHP functions for that like str-getcsv
Find the correct line inside the array with either array_filter or a simple foreach loop.
Update the respective value with the new price
Create a CSV file from the array with fputcsv
This is the controller. I update the image but I think input type file not accept file or not send the file to the controller so my code was not working well. I think controller code is true.
class OurTeam extends CI_Controller {
public function UpdateTeam()
{
$config['image_library'] = 'gd2';
$config['upload_path'] = '../employeephoto/';
$config['source_image'] ='employeephoto/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 12024;
$config['width'] = 300;
$config['height'] = 150;
$this->load->library('upload', $config);
$img = $_FILES['fileupdate']['name'];
if($img)
{
if (!$this->upload->do_upload('fileupdate'))
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
$file_name=($this->upload->data('file_name'));
$this->load->model('OurTeamModel');
$id= $_POST['id'];
$removeimg = $this->OurTeamModel->SelectById($id);
echo $imgpath = 'employeephoto/'.$removeimg[0]->img;
if(file_exists($imgpath))
{
unlink($imgpath);
}
else
{
echo "no";
}
$this->OurTeamModel->UpdateOurTeam($file_name);
$config['image_library'] = 'gd2';
$config['upload_path'] = '../employeephoto/'.$file_name;
$config['source_image'] = '../employeephoto/'.$file_name;
$config['maintain_ratio'] = false;
$config['allowed_types'] = 'gif|jpg|png';
$config['width'] = 660;
$config['height'] = 300;
$this->load->library('image_lib', $config);
$this->image_lib->clear();
$this->image_lib->initialize($config);
$ok = $this->image_lib->resize();
}
}
else
{
$this->load->model('OurTeamModel');
$this->OurTeamModel->UpdateOurTeamRecord();
}
redirect('admin/OurTeam');
}
}
This is view page
<?php echo form_open_multipart('admin/OurTeam/UpdateTeam');?>
<input type="file" name="fileupdate" size="20" id="fileupdate">
<input type="submit" value="Save" >
</form>
Please change to
From:
$config['image_library'] = 'gd2';
$config['upload_path'] = '../employeephoto/';
$config['source_image'] ='employeephoto/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 12024;
$config['width'] = 300;
$config['height'] = 150;
TO:
$config['upload_path'] = './employeephoto/';
$config['allowed_types'] = 'gif|jpg|png|doc|txt';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
I have checked your code. Please do one thing this article and follow step by step. Hope this will make sense.
https://www.tutorialspoint.com/codeigniter/codeigniter_file_uploading.htm
Here is the step by step explanation how to upload a file in CodeIgniter.
Try this and let me know what is outputting (maybe take a printsrc and upload to imgur):
public function UpdateTeam() {
$config['image_library'] = 'gd2';
$config['upload_path'] = '../employeephoto/';
//$config['source_image'] = 'employeephoto/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 12024;
$config['width'] = 300;
$config['height'] = 150;
$this->load->library('upload', $config);
if (!empty($_FILES['fileupdate']['name'])) {
if (!$this->upload->do_upload('fileupdate')) {
echo 'upload failed with error: <br>';
exit($this->upload->display_errors());
} else {
echo 'upload passed <br>';
$file_name = ($this->upload->data('file_name'));
$this->load->model('OurTeamModel');
$id = $_POST['id'];
$removeimg = $this->OurTeamModel->SelectById($id);
echo $imgpath = 'employeephoto/' . $removeimg[0]->img;
if (file_exists($imgpath)) {
unlink($imgpath);
} else {
echo "no";
}
$this->OurTeamModel->UpdateOurTeam($file_name);
echo 'resizing image <br>';
$config['image_library'] = 'gd2';
$config['upload_path'] = '../employeephoto/' . $file_name;
$config['source_image'] = '../employeephoto/' . $file_name;
$config['maintain_ratio'] = false;
$config['allowed_types'] = 'gif|jpg|png';
$config['width'] = 660;
$config['height'] = 300;
$this->load->library('image_lib', $config);
$this->image_lib->clear();
$this->image_lib->initialize($config);
if (!$this->image_lib->resize()) {
echo 'image resize failed <br>';
exit($this->image_lib->display_errors());
}
echo 'all good <br>';
}
} else {
echo 'no file <br>';
$this->load->model('OurTeamModel');
$this->OurTeamModel->UpdateOurTeamRecord();
}
//redirect('admin/OurTeam');
}
I'm trying to display a json array with contents from my database but when their is accents in the database the json array doesn't want to be displayed, their is my code:
<?php
include 'connect.php';
header('Content-Type: text/plain; charset=UTF-8') ;
$serial = 1;
$statment = mysqli_prepare($conn, "SELECT * FROM lesson WHERE serial = ?");
mysqli_stmt_bind_param($statment, "i", $serial);
mysqli_stmt_execute($statment);
mysqli_stmt_store_result($statment);
mysqli_stmt_bind_result($statment, $serial, $by, $type, $description, $lesson, $nb_q);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statment)){
$response["success"] = true;
$response["serial"] = $serial;
$response["by"] = $by;
$response["type"] = $type;
$response["lesson"] = $lesson;
$response["description"] = $description;
$response["nb_q"] = $nb_q;
for ($i = 1; $i <= $nb_q; $i++) {
$statment2 = mysqli_prepare($conn, "SELECT * FROM question WHERE 4_l_id = ? AND q_num = ?");
mysqli_stmt_bind_param($statment2, "ii", $serial, $i);
mysqli_stmt_execute($statment2);
mysqli_stmt_store_result($statment2);
mysqli_stmt_bind_result($statment2, $question, $nb_answer, $type, $correct_1, $for_l_id, $id, $q_num);
while(mysqli_stmt_fetch($statment2)){
$response["q".$i] = $question;
}
}
}
echo json_encode($response, JSON_UNESCAPED_UNICODE);
?>
Thank you for your answers
I found a good code but thank you for your help,
<?php
include 'connect.php';
$serial = 1;
$statment = mysqli_prepare($conn, "SELECT * FROM lesson WHERE serial = ?");
mysqli_stmt_bind_param($statment, "i", $serial);
mysqli_stmt_execute($statment);
mysqli_stmt_store_result($statment);
mysqli_stmt_bind_result($statment, $serial, $by, $type, $description, $lesson, $nb_q);
$response = array();
$response["success"] = false;
function utf8_encode_all(&$value)
{
if (is_string($value)) return utf8_encode($value);
if (!is_array($value)) return $value;
$ret = array();
foreach($dat as $i=>$d) $ret[$i] = utf8_encode_all($d);
return $ret;
}
while(mysqli_stmt_fetch($statment)){
$response["success"] = true;
$response["serial"] = $serial;
$response["by"] = utf8_encode_all($by);
$response["type"] = utf8_encode_all($type);
$response["lesson"] = utf8_encode_all($lesson);
$response["description"] = utf8_encode_all($description);
$response["nb_q"] = $nb_q;
for ($i = 1; $i <= $nb_q; $i++) {
$statment2 = mysqli_prepare($conn, "SELECT * FROM question WHERE 4_l_id = ? AND q_num = ?");
mysqli_stmt_bind_param($statment2, "ii", $serial, $i);
mysqli_stmt_execute($statment2);
mysqli_stmt_store_result($statment2);
mysqli_stmt_bind_result($statment2, $question, $nb_answer, $type, $correct_1, $for_l_id, $id, $q_num);
while(mysqli_stmt_fetch($statment2)){
$response["q".$i] = utf8_encode_all($question);
}
}
}
$array = array_map('htmlentities',$response);
$json = html_entity_decode(json_encode($array));
echo $json;
?>
var imgAlums = window.document.getElementsByClassName("imgAlu");
var photos= [];
for (var i = 0; i < imgAlums.length; i++) {
photos.push(imgAlums[i].currentSrc);
}
//the photos array is filled //photos[0]=
data:image/;base64,/9j/4AAQSkZJRgABAQAAAQA...;
//photos[1]=data:image/;base64,/9j/4AAFWEJDKWMDCIWUEIOD...;
$.ajax({
type: 'POST',
url: '<?= URL_PROYECTO_SEGURO ?>/panel/assets/php/generateZipPhotos.php',
data: {"photos": JSON.stringify(photos)},
success: function (data) {
console.log(data);
alert("Operacion realizada con exito");
}
});
PHP code:
$nameZip = "test.zip";
$zip = new ZipArchive();
$zip->open($nameZip, ZipArchive::OVERWRITE);
$zip->addEmptyDir("Photos");
$photos= json_decode($_POST["photos"], true);
for ($i = 0; $i < count($photos); $i++) {
$data = $photos[$i];
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$zip->addFromString("Photos/Photo" . $i . ".png", $data);
}
$zip->close();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$nameZip");
header("Content-Transfer-Encoding: binary");
readfile($nameZip);
unlink($nameZip);
But does not generate the zip file correctly.
[edit]The zip file is generated but this has nothing inside. The problem is when you write in the zip file. The photo is misspelled
I am running into issues when uploading an image sent to PHP via JS. I can upload the image fine, but I would to resize the image before moving it to it's new destination. I can also rename the image without any issues. It's really just the resizing that is the issue here.
After a lot of searching I have seen a lot of questions regarding this on SO, which is how I got to where I am now, but not one that answers this 100%. If you know of a question/answer already on SO please link me to the correct article.
Any help is much appreciated, thanks.
Here is the JS
var test = document.querySelector('#afile');
test.addEventListener('change', function() {
var file = this.files[0];
var fd = new FormData();
fd.append('afile', file);
// These extra params aren't necessary but show that you can include other data.
fd.append('id', burgerId);
var xhr = new XMLHttpRequest();
// why wont this work in the actions directory?
xhr.open('POST', 'actions/upload.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
var uploadProcess = document.getElementById('uploadProcess');
uploadProcess.setAttribute('style', 'width: ' + percentComplete + '%;');
// uploadProcess.innerHTML = parseInt(percentComplete) + '% uploaded';
}
};
xhr.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.response);
image = 'img/' + resp.newFileName;
sessionStorage.setItem('burgerLoc', image);
var image = document.createElement('img');
image.src = resp.dataUrl;
document.body.appendChild(image);
};
};
xhr.send(fd);
// upImage(id)
}, false);
Here is the markup
<input type="file" name="afile" id="afile" accept="image/*"/>
Here is the PHP
$image = $_FILES['afile']['name'];
$image_tmp = $_FILES['afile']['tmp_name'];
$image_type = $_FILES['afile']['type'];
function getName($str) {
$parts = explode('.',$str);
$imgName = str_replace(' ', '_',$parts[0]);
return $imgName;
}
function getExtension($str) {
$parts = explode('.',$str);
$ext = $parts[1];
return $ext;
}
$image_name = stripslashes($image);
$name = getName($image_name);
$image_ext = getExtension($image_name);
$ext = strtolower($image_ext);
if($ext == 'jpg' || $ext == 'jpeg' ) {
$ext = 'jpg';
$src = imagecreatefromjpeg($image_tmp);
} else if($ext == 'png') {
$src = imagecreatefrompng($image_tmp);
} else {
$src = imagecreatefromgif($image_tmp);
}
$file_content = file_get_contents($image_tmp);
$data_url = 'data:' . $image_type . ';base64,' . base64_encode($file_content);
list($width,$height) = getimagesize($image_tmp);
// width of the main image
$new_width = 748;
$new_height = ($height / $width) * $new_width;
$img_dest = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($img_dest,$src,0,0,0,0,$new_width,$new_height,$width,$height);
// rename the file
$new_file_name = strtolower($_REQUEST['id'] . '.' . $ext);
$new_file_location = '../img/' . $new_file_name;
imagejpeg($img_dest,$new_file_name,100);
move_uploaded_file($image_tmp, $new_file_location);
imagedestroy($src);
imagedestroy($img_dest);
$json = json_encode(array(
'dataUrl' => $data_url,
'extension' => $ext,
'id' => $_REQUEST['id'],
'name' => $image,
'newFileName' => $new_file_name,
'type' => $image_type
));
echo $json;
I would maybe try installing ImageMagick in your linux distribution and try to use this function to resize the image
http://php.net/manual/en/imagick.resizeimage.php
I have reproduced your script on my webserver... I have made modifications and came up with this.
The most significant modification is that I am using exact paths in the file locations, and that I am moving the tmp file to a real file, load that real file, resize that real file instead of trying it to do with the tmp uploaded file.
PHP:
<?php
$image = $_FILES['afile']['name'];
$image_tmp = $_FILES['afile']['tmp_name'];
$image_type = $_FILES['afile']['type'];
function getName($str) {
$parts = explode('.',$str);
$imgName = str_replace(' ', '_',$parts[0]);
return $imgName;
}
function getExtension($str) {
$parts = explode('.',$str);
$ext = $parts[1];
return $ext;
}
$image_name = stripslashes($image);
$name = getName($image_name);
$image_ext = getExtension($image_name);
$ext = strtolower($image_ext);
$outputfolder = "/var/www/html/wp-content/";
$new_file_name = strtolower($_REQUEST['id'] . '.' . $ext);
$new_file_location = $outputfolder.$new_file_name;
move_uploaded_file($image_tmp, $new_file_location);
if($ext == 'jpg' || $ext == 'jpeg' ) {
$ext = 'jpg';
$src = imagecreatefromjpeg($new_file_location);
} else if($ext == 'png') {
$src = imagecreatefrompng($new_file_location);
} else {
$src = imagecreatefromgif($new_file_location);
}
list($width,$height) = getimagesize($new_file_location);
// width of the main image
$new_width = 748;
$new_height = ($height / $width) * $new_width;
$img_dest = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($img_dest,$src,0,0,0,0,$new_width,$new_height,$width,$height);
$resizedLocation = $outputfolder."resized_".$new_file_name;
imagejpeg($img_dest,$resizedLocation,100);
imagedestroy($src);
imagedestroy($img_dest);
$file_content = file_get_contents($resizedLocation);
$data_url = 'data:image/jpeg;base64,' . base64_encode($file_content);
$json = json_encode(array(
'dataUrl' => $data_url,
'extension' => $ext,
'id' => $_REQUEST['id'],
'name' => $image,
'newFileName' => $new_file_name,
'type' => $image_type
));
echo $json;
?>
Your HTML/JS stays untouched.
Now this works for me flawlessly, the only thing you have to make sure
the $outputfolder is writeable by the linux user under which the webeserver executing the php script is runnging (typically web-data...)
My web server:
CentOS Linux release 7.0.1406 (Core)
php.x86_64 5.4.16-23.el7_0.3
apache x86_64 2.4.6