Create QR Codes by Function or Class - php

I'm using QRCode from Google API and I put this code in the function.
Now I want to show two images, for example: Two images with different sizes or datas!
It does not matter if you use class or function, I just want to get different output on the page.
This is code:
<?php
function CreateQRCode($data, $size, $logo) {
header('Content-type: image/png');
// Get QR Code image from Google Chart API
// http://code.google.com/apis/chart/infographics/docs/qr_codes.html
$QR = imagecreatefrompng('https://chart.googleapis.com/chart?cht=qr&chld=H|1&chs='.$size.'&chl='.urlencode($data));
if($logo !== FALSE){
$logo = imagecreatefromstring(file_get_contents($logo));
$QR_width = imagesx($QR);
$QR_height = imagesy($QR);
$logo_width = imagesx($logo);
$logo_height = imagesy($logo);
// Scale logo to fit in the QR Code
$logo_qr_width = $QR_width/3;
$scale = $logo_width/$logo_qr_width;
$logo_qr_height = $logo_height/$scale;
imagecopyresampled($QR, $logo, $QR_width/3, $QR_height/3, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
}
imagepng($QR);
imagedestroy($QR);
}
CreateQRCode('http://google.com', '200x200', FALSE);
?>
Like this:
example 2
example 1

Related

Display Bar code image giving Charactar is not allowed

with help of below code, i successfully displaying tracking_id in pdf , Now i am trying to displaying bar code image....
Its working fine if i use static value . but when i passed column value instead of static value it gave error :
Static : $text = isset($_GET['text']) ? $_GET['text'] : "1234";
:
Dynamic :
$text = isset($_GET['text']) ? $_GET['text'] : $tracking_id;
Result :
I guess I am passing tracking_id column value not in proper manner :
<?php
$con = mysqli_connect("localhost","root","iJ564645qA9v3J","do_management4");
include('database.php');
$result = mysqli_query($con,"SELECT * FROM orders");
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
$tracking_id = $row['tracking_id'];
}
$database = new Database();
$result = $database->runQuery("SELECT tracking_id FROM orders where id = '".$_REQUEST['id']."'");
$header = $database->runQuery("SELECT UCASE(`COLUMN_NAME`)
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='do_management4'
AND `TABLE_NAME`='orders'
and `COLUMN_NAME` in ('tracking_id')");
require __DIR__ . '/../vendor/autoload.php';
use BarcodeBakery\Barcode\BCGcode11;
// Loading Font
$font = new BCGFontFile(__DIR__ . '/../font/Arial.ttf', 18);
// Don't forget to sanitize user inputs
$text = isset($_GET['text']) ? $_GET['text'] : $tracking_id;
// The arguments are R, G, B for color.
$color_black = new BCGColor(0, 0, 0);
$color_white = new BCGColor(255, 255, 255);
$drawException = null;
try {
$code = new BCGcode11();
$code->setScale(2); // Resolution
$code->setThickness(30); // Thickness
$code->setForegroundColor($color_black); // Color of bars
$code->setBackgroundColor($color_white); // Color of spaces
$code->setFont($font); // Font (or 0)
$code->parse($text); // Text
} catch (Exception $exception) {
$drawException = $exception;
}
$drawing = new BCGDrawing('', $color_white);
if ($drawException) {
$drawing->drawException($drawException);
} else {
$drawing->setBarcode($code);
$drawing->draw();
}
// Header that says it is an image (remove it if you save the barcode to a file)
header('Content-Type: image/png');
header('Content-Disposition: inline; filename="barcode.png"');
// Draw (or save) the image into PNG format.
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
?>
Considering the documentation BCGcode11 allows only the numbers from 0 to 9 and a hyphen (-)
You either can
Remove the unwanted characters from $tracking_id which may lead to wrong datas
Use the proper class for the barecode you want.
BCGcode39 allows more characters to build your barecode : Code 39 contains all the capital letters, the numbers from 0 to 9, the following special characters "-.$/+%" and spaces.
Use BCGcode39 it allows you to use more characters lik capital letters and some special characters. or keep using BCGcode11 but then you need to remove the unallowed characters.

Get YouTube video thumbnail and use it with PHP

How can I access thumbnail collection of a YouTube video using the link of the video from the YouTube API.
I want thumbnails to be displayed on website using PHP using the video id stored in a variable for example $link
YouTube stores many different types of thumbnails on its server for different devices. You can access it by using the video id which
every YouTube video has. You can display the images on your website using a variable $link which holds the id of the video and substituting it
in the place for video_ID in the link.
Low quality thumbnail:
http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/sddefault.jpg
Medium quality thumbnail:
http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/mqdefault.jpg
High quality thumbnail:
http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/hqdefault.jpg
Maximum quality thumbnail:
http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/maxresdefault.jpg
Example:
If you want to access the thumbnail of the following video:
https://www.youtube.com/watch?v=Q-GYwhqDo6o
Video ID : Q-GYwhqDo6o
So, this is how video thumbnail link looks like:
http://img.youtube.com/vi/Q-GYwhqDo6o/mqdefault.jpg
Hope it helps. Enjoy coding.
To get high-quality image you can use the following URL which is fetched from youtube API
$video_id = explode("?v=", $link);
$video_id = $video_id[1];
$thumbnail="http://img.youtube.com/vi/".$video_id."/maxresdefault.jpg";
You can use the below code. It is work for me. Choose the image quality as per your requirement.
<?php
$youtubeID = getYouTubeVideoId('youtube video url');
$thumbURL = 'https://img.youtube.com/vi/' . $youtubeID . '/mqdefault.jpg';
print_r($thumbURL);
function getYouTubeVideoId($pageVideUrl) {
$link = $pageVideUrl;
$video_id = explode("?v=", $link);
if (!isset($video_id[1])) {
$video_id = explode("youtu.be/", $link);
}
$youtubeID = $video_id[1];
if (empty($video_id[1])) $video_id = explode("/v/", $link);
$video_id = explode("&", $video_id[1]);
$youtubeVideoID = $video_id[0];
if ($youtubeVideoID) {
return $youtubeVideoID;
} else {
return false;
}
}
?>
here is my handy function to download the Youtube thumbnail image
function downloadYouTubeThubnailImage($youTubeLink='',$thumbNamilQuality='',$fileNameWithExt='',$fileDownLoadPath='')
{
$videoIdExploded = explode('?v=', $youTubeLink);
if ( sizeof($videoIdExploded) == 1)
{
$videoIdExploded = explode('&v=', $youTubeLink);
$videoIdEnd = end($videoIdExploded);
$removeOtherInVideoIdExploded = explode('&',$videoIdEnd);
$youTubeVideoId = current($removeOtherInVideoIdExploded);
}else{
$videoIdExploded = explode('?v=', $youTubeLink);
$videoIdEnd = end($videoIdExploded);
$removeOtherInVideoIdExploded = explode('&',$videoIdEnd);
$youTubeVideoId = current($removeOtherInVideoIdExploded);
}
switch ($thumbNamilQuality)
{
case 'LOW':
$imageUrl = 'http://img.youtube.com/vi/'.$youTubeVideoId.'/sddefault.jpg';
break;
case 'MEDIUM':
$imageUrl = 'http://img.youtube.com/vi/'.$youTubeVideoId.'/mqdefault.jpg';
break;
case 'HIGH':
$imageUrl = 'http://img.youtube.com/vi/'.$youTubeVideoId.'/hqdefault.jpg';
break;
case 'MAXIMUM':
$imageUrl = 'http://img.youtube.com/vi/'.$youTubeVideoId.'/maxresdefault.jpg';
break;
default:
return 'Choose The Quality Between [ LOW (or) MEDIUM (or) HIGH (or) MAXIMUM]';
break;
}
if( empty($fileNameWithExt) || is_null($fileNameWithExt) || $fileNameWithExt === '')
{
$toArray = explode('/',$imageUrl);
$fileNameWithExt = md5( time().mt_rand( 1,10 ) ).'.'.substr(strrchr(end($toArray),'.'),1);
}
if (! is_dir($fileDownLoadPath))
{
mkdir($fileDownLoadPath,0777,true);
}
file_put_contents($fileDownLoadPath.$fileNameWithExt, file_get_contents($imageUrl));
return $fileNameWithExt;
}
Function Description
Argumemts
$youTubeLink Youtube url for example https://www.youtube.com/watch?v=a3ICNMQW7Ok
$thumbNamilQuality It has Many Quality Such as LOW ,MEDIUM, HIGH, MAXIMUM
Thumbnail Quality list Taken from
https://stackoverflow.com/a/32346348/8487424
&&
https://stackoverflow.com/a/47546113/8487424
$fileNameWithExt File Name with Extension**for example** myfavouriteimage.png
NOTE $fileNameWithExt is not mandatory it will generate the uuid based file name
for Example 91b2a30d0682058ebda8d71606f5e327.jpg
if you want to put the file to the custom directory use this argument
NOTE $fileDownLoadPath is not mandatory it will generate the image file where the script is executing
Some of the sample examples
$folderpath = 'c:'.DIRECTORY_SEPARATOR.'xampp'.DIRECTORY_SEPARATOR.'htdocs'.DIRECTORY_SEPARATOR.'youtube'.DIRECTORY_SEPARATOR;
$imageName = 'mybeautfulpic.jpg';
downloadYouTubeThubnailImage('https://www.youtube.com/watch?v=a3ICNMQW7Ok','MAXIMUM',null,$folderpath );
downloadYouTubeThubnailImage('https://www.youtube.com/watch?v=a3ICNMQW7Ok','LOW',$imageName ,null);
Hope it is answered already but this function has some exta features
Google changed API on v.3 and those code from Python work exactly! You can use for PHP.
def get_small_image_url(self):
return 'http://img.youtube.com/vi/%s/%s.jpg' % (self.video_id, random.randint(1, 3))
def get_hqdefault(self):
return 'http://i1.ytimg.com/vi/%s/hqdefault.jpg' % self.video_id
def get_mqdefault(self):
return 'http://i1.ytimg.com/vi/%s/mqdefault.jpg' % self.video_id
def get_sddefault(self):
return 'http://i1.ytimg.com/vi/%s/sddefault.jpg' % self.video_id
def get_video_id(self, url):
link = urlparse.urlparse(url)
if link.hostname == 'youtu.be':
return link.path[1:]
if link.hostname in ('www.youtube.com', 'youtube.com'):
if link.path == '/watch':
state = urlparse.parse_qs(link.query)
return state['v'][0]
if link.path[:7] == '/embed/':
return link.path.split('/')[2]
if link.path[:3] == '/v/':
return link.path.split('/')[2]
return False
def get_meta(self, video_id):
api_token = **'here your API_Token'**
url = 'https://www.googleapis.com/youtube/v3/videos?part=snippet&id=%s&key=%s' % (video_id, api_token)
response = json.load(urllib.urlopen(url))
print response
context = {
'title': response['items'][0]['snippet']['localized']['title'],
'desc': response['items'][0]['snippet']['localized']['description']
}
return context
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
video_id = self.get_video_id(self.url)
meta = self.get_meta(video_id)
self.video_id = video_id
self.title = meta['title']
self.description = meta['desc']
super(Videos, self).save(
force_insert=force_insert,
force_update=force_update,
using=using,
update_fields=update_fields
)
the simplest and easiest way to get youtube-video-id from a youtube link using str_replace.
$youtube_ids = str_replace("https://www.youtube.com/watch?v=", "", "https://www.youtube.com/watch?v=QBKdaUv5YaI");
echo 'http://img.youtube.com/vi/'.$youtube_ids.'/maxresdefault.jpg';
Low-quality thumbnail:
echo 'http://img.youtube.com/vi/'.$youtube_ids.'/sddefault.jpg';
Medium quality thumbnail:
echo 'http://img.youtube.com/vi/'.$youtube_ids.'/mqdefault.jpg';
High quality thumbnail:
echo 'http://img.youtube.com/vi/'.$youtube_ids.'/hqdefault.jpg';
Maximum quality thumbnail:
echo 'http://img.youtube.com/vi/'.$youtube_ids.'/maxresdefault.jpg';

How do I print a barcode using barcode generator for PHP onto a pdf formatted page where I want it?

Alright so first things first:
I've searched over this site for 6+ hours and I keep coming up with the same results. The main answer I keep getting is: How to Generate Barcode using PHP and Display it as an Image on the same page
But this is not working for me. Even the answer on that page that was accepted ends with "After you have added all the codes, you will get this way:" which is so vague I feel like I'm supposed to already be an expert to understand it. I'm getting frustrated with this problem because I cannot seem to find any "moron directions" that can help me understand how everything works in this library for barcode generator for php.
Here is what I have:
I'm using fpdf to print a pdf file which works great!
Page Name: PrintMyPDF.php
<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);
$thisorderID = $_GET['Xort'];
require ('UFunctions.php');
if (trim($thisorderID) == ""){
$value = '0';
}
if (!is_digit($thisorderID) || $thisorderID < 0)
{
header('Location:ErrorInt.php');
exit;
}
//Database connection established
require_once('DBASEConnector.php');
$sql2 = "SELECT users.name, users.storenum, users.storename, Orders.OrderID, Orders.name
FROM users, Orders
WHERE Orders.name = users.name
AND Orders.OrderID = '$thisorderID'";
$result = $db->query($sql2);
$row = $result->fetch_assoc();
$ThisStoreNum = $row['storenum'];
$ThisStoreName = $row['storename'];
require('fpdf.php');
$pdf = new FPDF();
//$fpdf->SetMargins(0, 0, 0);
//$fpdf->SetAutoPageBreak(true, 0);
$pdf->SetAuthor('Walter Ballsbig');
$pdf->SetTitle('Order Form');
$pdf->SetFont('Helvetica','B',16);
$pdf->SetTextColor(0,0,0);
$pdf->AddPage('P');
$pdf->SetDisplayMode(real,'default');
$pdf->SetXY(50,20);
$pdf->SetDrawColor(0,0,0);
$pdf->Cell(100,10,'Order Form',1,1,'C',0);
$pdf->SetFontSize(10);
$pdf->SetX(50);
$pdf->Cell(100,10, 'Order: '.$thisorderID.' | Store: '.$ThisStoreNum.'-'.$ThisStoreName,1,1,'C',0);
$pdf->SetXY(10,50);
$pdf->SetFontSize(12);
$pdf->Cell(6,6,'X',1,0,'C',0);
$pdf->Cell(14,6,'QTY',1,0,'C',0);
$pdf->Cell(130,6, 'ITEM',1,0,'C',0);
$pdf->Cell(30,6, 'UNIT',1,1,'C',0);
$query = "SELECT Inventory.ProductI, Inventory.ProductName, Inventory.CurrentQty, Inventory.Pull, Inventory.Unit, OrderItems.ProductI, OrderItems.QtyO, OrderItems.OrderI
FROM Inventory, OrderItems
WHERE OrderItems.OrderI = '$thisorderID'
AND OrderItems.ProductI = Inventory.ProductI
ORDER BY Inventory.Pull, Inventory.ProductName";
$result = $db->query($query);
$num_results = $result->num_rows;
for ($i=0; $i <$num_results; $i++)
{
$row = $result->fetch_assoc();
$pdf->SetFontSize(12);
IF ($row['CurrentQty'] <=0)
{
$pdf->SetFontSize(10);
$pdf->Cell(6,6,'BO',1,0,'C',0);
$pdf->SetFontSize(12);
}else{
$pdf->Cell(6,6,' ',1,0,'C',0);
}
$pdf->Cell(14,6, $row['QtyO'],1,0,'C',0);
$pdf->Cell(130,6, $row['ProductName'],1,0,'L',0);
$pdf->Cell(30,6, $row['Unit'],1,1,'C',0);
}
$pdf->Output();
$db->close();
?>
This prints up my pdf beautifully! Now I wanted to add a barcode on the page that will represent the order number for scanning purposes.
Now here is what I have for my code that contains the barcode... code.
Name of barcode page: BarCodeIt.php
<?php
function BarCodeIt($MyID) {
// Including all required classes
require_once('./class/BCGFontFile.php');
require_once('./class/BCGColor.php');
require_once('./class/BCGDrawing.php');
// Including the barcode technology
require_once('./class/BCGcode39.barcode.php');
// Loading Font
$font = new BCGFontFile('./font/Arial.ttf', 18);
// Don't forget to sanitize user inputs
$text = isset($_GET['text']) ? $_GET['text'] : $MyID;
// The arguments are R, G, B for color.
$color_black = new BCGColor(0, 0, 0);
$color_white = new BCGColor(255, 255, 255);
$drawException = null;
try {
$code = new BCGcode39();
$code->setScale(2); // Resolution
$code->setThickness(30); // Thickness
$code->setForegroundColor($color_black); // Color of bars
$code->setBackgroundColor($color_white); // Color of spaces
$code->setFont($font); // Font (or 0)
$code->parse($text); // Text
} catch(Exception $exception) {
$drawException = $exception;
}
/* Here is the list of the arguments
1 - Filename (empty : display on screen)
2 - Background color */
$drawing = new BCGDrawing('', $color_white);
if($drawException) {
$drawing->drawException($drawException);
} else {
$drawing->setBarcode($code);
$drawing->draw();
}
//Header that says it is an image (remove it if you save the barcode to a file)
header('Content-Type: image/png');
header('Content-Disposition: inline; filename="barcode.png"');
// Draw (or save) the image into PNG format.
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
}
?>
Now in my PDF file just before this line:
$pdf->Output();
I have added this:
$pdf->AddPage('P');
$pdf->SetDisplayMode(real,'default');
require('/BarCodeIt.php');
$MyBarCode = BarCodeIt($thisorderID);
echo $MyBarCode;
But what it does is all of my other pdf elements disappear and I'm left with only a big barcode (the right one! that part works) but that's all that is on the screen. It's like when the barcode section runs it negates everything else and just prints the barcode. I want to print just the barcode where I want it on the PDF but I'm not clever enough to figure out what I'm doing wrong. Any help on this would be greatly appreciated.
In $pdf->SetDisplayMode(real,'default');, real is not an identifier. I believe you've forgotten the $ prefix.
Have you warnings reporting at maximum level? If not, include:
error_reporting(E_ALL);
in your script and see that it shows additional issues.
I'm not familiar with fpdf, but what you are doing seems wrong just by looking at it: Everywhere you add elements to your pdf by using methods on your $pdf object like $pdf->... and when you want to add the barcode, you echo it out directly.
Don't echo your image out. Instead get rid of the header() calls in your barcode script, save your image and look for the right method to add an image to the $pdf object.
Here is a question with answers that deals with adding an image: Inserting an image with PHP and FPDF

When resizing an image with PHP, the page goes blank

I'm fairly new to PHP. I have a function written to scale an image and save a thumbnail. The function is working (thumbnails being created) but any time it runs the the page loads a blank page with only an empty image tag - I can't view the source of the page (because there isn't one?).
If the function doesn't run the page loads fine.
function scaleImage($id)
{
header("Content-Type: image/jpeg");
$si = imagecreatefromjpeg("img/dribbble/standard_resolution/{$id}.jpg");
$si_x = imagesx($si);
$si_y = imagesy($si);
$di_x = 210;
$di_y = 158;
$di = imagecreatetruecolor($di_x, $di_y);
imagecopyresampled($di, $si, 0, 0, 0, 0, $di_x,
$di_y, $si_x, $si_y);
imagejpeg($di,"img/dribbble/low_resolution/{$id}.jpg",90);
};
Why is the page blank when the function runs and how can I fix this?
Try outputting image without $filename argument: imagejpeg($di, null, 90);

View image in the image field of the php

Good day!
Could anyone help me, there is a system where users do register via their desktop in a database hosted on the web, we are now developing the web interface of this system, then it has a certain functionality in the system where I have to display the photo user.
I do what normal SELECT in SQL Server, but upon the imagejpeg ($ img); it does not show the whole picture, just a piece of the picture. Could anyone help me? I'm looking for some tutorials on the web and they speak it is because of the size of the field. If the field is of type (image) and the return is in hexadecimal.
Below I tried to do a function with the help of a friend, but she also did not work:
<php
$id = (int)$_GET['id'];
$qryimg = mssql_query(gimage SELECT FROM user WHERE id = {$ id});
$resimg = mssql_fetch_array($qryimg);
$im1 = $resimg['gimage'];
header("Content-type: image/jpg");
$image='';
for($i=2; $i<strlen($im1); $i+=2)
{
$hex = $im1{$i} . $im1{($i + 1)};
$cod = hexdec( $hex );
$image .= chr( $cod );
}
echo $image;
#echo imagejpeg($image);
?>
Why doesn't the following code work? Can't you just echo the image.
<php
$id = (int)$_GET['id'];
$qryimg = mssql_query(gimage SELECT FROM user WHERE id = {$ id});
$resimg = mssql_fetch_array($qryimg);
$im1 = $resimg['gimage'];
header("Content-type: image/jpg");
print $im1;
exit;
What field type is gimage?

Categories