Cannot display blob image from database using PHP - php

I am not able to get my broswer to display an image from the database(stored as blob). I have tried
header("Content-type: image/jpeg");
echo '';
But it is still not able to display on the browser.
getImage.php
<?php
require_once 'php-activerecord/ActiveRecord.php';
ActiveRecord\Config::initialize(function($cfg) {
$cfg->set_model_directory('models');
$cfg->set_connections(array(
'development' => 'mysql://root:mysql#localhost/BondingTogether'));
});
$id = addslashes($_REQUEST['id']);
$row = food::find_by_foodid($id);
$image = $row->image;
//$image = ""
//header("Content-Type: image/jpg");
header("Content-type: image/jpeg");
//echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'"/>';
echo $image;
//echo base64_decode($image);
Adding to the database
<?php
require_once 'php-activerecord/ActiveRecord.php';
ActiveRecord\Config::initialize(function($cfg) {
$cfg->set_model_directory('models');
$cfg->set_connections(array(
'development' => 'mysql://root:mysql#localhost/BondingTogether'));
});
//files
$file = $_FILES['foodimage']['tmp_name'];
if (!isset($file)) {
}
else {
//$image = addslashes(file_get_contents($_FILES['foodimage']['tmp_name']));
$image_name = addslashes($_FILES['foodimage']['tmp_name']);
$image_size = getimagesize($_FILES['foodimage']['tmp_name']);
if ($image_size == FALSE) {
die('Please select an image file');
} else {
}
}
$image = addslashes(file_get_contents($_FILES['foodimage']['tmp_name']));
//$image = chunk_split(base64_encode(file_get_contents("image.jpg")));
Food::create(array(
'xcoord' => $_POST['XCoord']
, 'ycoord' => $_POST['YCoord']
, 'title' => $_POST['title']
, 'category' => $_POST['cat']
, 'description' => $_POST['desc']
, 'image' => $image
));

You should not be using addslashes() when storing image data in your DB. A better alternative is to insert the image data with base64_encode(), and base64_decode() it when you output it. A simple search will find plenty of good answers to this and similar questions

Related

Generate thumbnail from video using ffmpeg and add to mysql database

Im a noobie in php but still im trying :) Im making bulk video uploader/importer to database. Looking ideas how to extract thumbnails from videos on upload and add those thumbnails to mysql database for each video... :/ Im trying using ffmpeg, but i dont found the way how to implement it to my code...
<?php
// Database
include 'config/database.php';
if(isset($_POST['submit'])){
$url = "localhost/";
$uploadsDir = "uploads/";
$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
// Velidate if files exist
if (!empty(array_filter($_FILES['fileUpload']['name']))) {
// Loop through file items
foreach($_FILES['fileUpload']['name'] as $title=>$val){
// Get files upload path
$fileName = $_FILES['fileUpload']['name'][$title];
$tempLocation = $_FILES['fileUpload']['tmp_name'][$title];
$targetFilePath = $uploadsDir . $fileName;
$fileType = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));
$withOutExtension = pathinfo($fileName, PATHINFO_FILENAME);
$uploadDate = date('Y-m-d H:i:s');
$uploadOk = 1;
if(in_array($fileType, $allowedExts)){
if(move_uploaded_file($tempLocation, $targetFilePath)){
$sqlVal = $withOutExtension;
$sqlVal2 = $url . $uploadsDir . $fileName;
$sqlVal3 = null;
$randomID = rand(1000, 999999);
$sqlVal4 = ('<p><video controls="" src="/' . $sqlVal2 . '" width="640" height="360" class="note-video-clip"></video><br></p>');
$slug = str_replace(' ', '-', $withOutExtension);;
$file = $uploadsDir . $fileName;
$filesize = filesize($file); // bytes
$filesize = round($filesize / 1024 / 1024, 1);
} else {
$response = array(
"status" => "alert-danger",
"message" => "File coud not be uploaded."
);
}
} else {
$response = array(
"status" => "alert-danger",
"message" => "I want mp4 file."
);
}
// Add into MySQL database
if(!empty($sqlVal)) {
$insert = $conn->query("INSERT INTO applications (id, title, description, custom_description, details, image, slug, file_size, license, developer, url, buy_url, type, votes, screenshots, total_votes, counter, hits, category, platform, must_have, featured, pinned, editors_choice, created_at, updated_at) VALUES ('$randomID', '$sqlVal', 'Video .mp4 Live Wallpaper. Animated wallpaper is a cross between a screensaver and desktop wallpaper. Like a normal wallpaper, an animated wallpaper serves as the background on your desktop, which is visible to you only when your workspace is empty, i.e. no program windows block it from view.', '$sqlVal3', '$sqlVal4', '99999.jpg', '$slug', '$filesize MB', 'free', 'n/a', '$sqlVal2', '$sqlVal3', '1', '0.00', '', '0', '0', '1', '22', '6', '1', '1', '0', '1', '2021-11-11 16:55:36', '2021-11-11 16:55:36')");
if($insert) {
$response = array(
"status" => "alert-success",
"message" => "Files successfully uploaded."
);
} else {
$response = array(
"status" => "alert-danger",
"message" => "Files coudn't be uploaded due to database error."
);
}
}
}
} else {
// Error
$response = array(
"status" => "alert-danger",
"message" => "Please select a file to upload."
);
}
}
?>
Concerning the FFMpeg part, I think a good way to start is to actually use the PHP-FFMpeg library. The Basic Usage section in the documentation contains an example on how to generate a frame for a given video:
require 'vendor/autoload.php';
$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open('video.mpg');
$video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(10))
->save('frame.jpg');
A simplified process would be as follows:
The user uploads a video, after which the video gets moved to a different
directory.
Now you can use the snippet above, with the frame method to get a thumbnail for your video.
After the image saving is done, you just need to add it to your database.
If the thumbnails refer to the image column in your table, you can get away with just inserting the filename, frame.jpg (or even the complete filepath, /public/path/to/frame.jpg).
If the thumbnails refer to the screenshots column in your table, and you want to have multiple thumbnails for your video, then you should consider creating a new table with a one-to-many relationship (from your video/application to a new table, e.g. thumbnails)
Then when the user gets to a page where the image should be displayed, just select it from the table and display it with an <img> tag (with the public filepath).
I would also strongly recommend not to save the complete <video> tag into your database, but instead add it to the page where you actually want to show your video.
Example:
<?php
$result = $conn->query('SELECT ...');
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<video src="<?php echo $row['video-column-path']; ?>"</video>
<?php
}
} else {
?>
No videos here
<?php
}
$conn->close();
?>
Found solution, now need to understand how to import generated thumbnail url to database field for video...
// Velidate if files exist
if (!empty(array_filter($_FILES['fileUpload']['name']))) {
// Loop through file items
foreach($_FILES['fileUpload']['name'] as $title=>$val){
// Get files upload path
$fileName = $_FILES['fileUpload']['name'][$title];
$tempLocation = $_FILES['fileUpload']['tmp_name'][$title];
$targetFilePath = $uploadsDir . $fileName;
$fileType = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));
$withOutExtension = pathinfo($fileName, PATHINFO_FILENAME);
$uploadDate = date('Y-m-d H:i:s');
$uploadOk = 1;
$randomID = rand(1000, 999999);
//Get one thumbnail from the video
$ffmpeg = "C:\\ffmpeg\\bin\\ffmpeg";
//echo $ffmpeg;
$imageFile = 'pic/thumb_'.time().'_'.$randomID.'.jpg';
$size = "120x90";
$getFromSecond = 1;
echo $cmd = "$ffmpeg -i $tempLocation -an -ss $getFromSecond -s $size $imageFile";
echo "<br>";
if(!shell_exec($cmd)){
echo "Thumbnail Created!";
}else{
echo "Error creating Thumbnail";
}

Imagick PHP (How to resize each image from database?)

I have been trying to resize each image from database before pushing it into an array. The array contains the image path(URL) where I would like to display the resize image onto a grid view as the original images are too big and takes too long to load, hence the resizing. I have been figuring out the logic and still couldn't solve it. Could anyone help me with this? My database contains columns 'photo' and 'location'.
getphoto.php
<?php
require_once('dbConnect.php');
$sql = "select * from volleyupload1";
$res = mysqli_query($con, $sql);
$result = array();
while ($row = mysqli_fetch_array($res)) {
foreach ($result as $row['photo']) {
$imagick = new Imagick($row['photo']);
$imagick->thumbnailImage(300, 300, true, true);
header("Content-Type: image/jpg");
// echo $imagick;
}
array_push($result, array('url' => $row['photo'], 'location' => $row['location']));
// $test = $row['photo'];
// foreach ($result as $row['photo']){
// $imagick = new Imagick($row['photo']);
// $imagick->thumbnailImage(300, 300, true, true);
// header("Content-Type: image/jpg");
// echo $imagick;
//
// }
}
echo json_encode(array("result" => $result));
mysqli_close($con);
I don't get the difference between 'photo' and 'location'. To the browser you should only send URLs not local filepaths.
Anyway, you need to store the thumbnail image to a new file and then return the url to this file instead of the original one.
Could look like this:
while ($row = mysqli_fetch_array($res)) {
$imagick = new Imagick($row['photo']);
$imagick->thumbnailImage(300, 300, true, true);
$thumb_path = $row['photo'] . '.thumb.jpg';
$thumb = fopen($thumb_path, 'w'); //open new filehandle to write the thumb
$imagick->writeImageFile($thumb);
fclose($thumb);
array_push($result, array('url' => $thumb_path, 'location' => $row['location']));
}
$thumb_path needs to be a local file path. To the browser you need to send a URL which is reachable from the internet

PHP & Jquery FileAPI - shared PHP server configuration

I'm letting my users crop & upload their image with jQuery FileAPI. I'm calling this PHP file with jQuery from another page.
Everything works good on my local server, but when uploading it to my production (shared - cPanel) server, it does not create the file.
Do you know if there is something that I need to change on my cPanel or call my hosting company for?
I tried tweeking with header access but nothing works.
Here is the PHP file:
<?php include 'init.php'; ?>
<?php
if(logged_in() === false) {
header('Location: login.php');
exit();
} ?>
<?php
/**
* FileAPI upload controller (example)
*/
include 'FileAPI.class.php';
if( $_SERVER['REQUEST_METHOD'] == 'OPTIONS' ){
exit;
}
if( strtoupper($_SERVER['REQUEST_METHOD']) == 'POST' ){
$files = FileAPI::getFiles(); // Retrieve File List
$images = array();
// Fetch all image-info from files list
fetchImages($files, $images);
// JSONP callback name
$jsonp = isset($_REQUEST['callback']) ? trim($_REQUEST['callback']) : null;
// JSON-data for server response
$json = array(
'images' => $images
, 'data' => array('_REQUEST' => $_REQUEST, '_FILES' => $files)
);
// Server response: "HTTP/1.1 200 OK"
FileAPI::makeResponse(array(
'status' => FileAPI::OK
, 'statusText' => 'OK'
, 'body' => $json
), $jsonp);
exit;
}
function fetchImages($files, &$images, $name = 'file'){
if( isset($files['tmp_name']) ){
$filename = $files['tmp_name'];
list($mime) = explode(';', #mime_content_type($filename));
if( strpos($mime, 'image') !== false ){
$size = getimagesize($filename);
$base64 = base64_encode(file_get_contents($filename));
$images[$name] = array(
'width' => $size[0]
, 'height' => $size[1]
, 'mime' => $mime
, 'size' => filesize($filename)
, 'dataURL' => 'data:'. $mime .';base64,'. $base64
);
$iWidth = $iHeight = 330; // desired image result dimensions
$iJpgQuality = 100;
// new unique filename
$sTempFileName = 'userpics/' . md5(time().rand());
// move uploaded file into cache folder
move_uploaded_file($filename, $sTempFileName);
// change file permission to 644
#chmod($sTempFileName, 0644);
if (file_exists($sTempFileName) && filesize($sTempFileName) > 0) {
$aSize = getimagesize($sTempFileName); // try to obtain image info
if (!$aSize) {
#unlink($sTempFileName);
return;
}
// check for image type
switch($aSize[2]) {
case IMAGETYPE_JPEG:
$sExt = '.jpg';
// create a new image from file
$vImg = #imagecreatefromjpeg($sTempFileName);
break;
case IMAGETYPE_GIF:
$sExt = '.gif';
// create a new image from file
$vImg = #imagecreatefromgif($sTempFileName);
break;
case IMAGETYPE_PNG:
$sExt = '.png';
// create a new image from file
$vImg = #imagecreatefrompng($sTempFileName);
break;
default:
#unlink($sTempFileName);
return;
}
$data = getimagesize($sTempFileName);
$width = $data[0];
$height = $data[1];
// create a new true color image
$vDstImg = #imagecreatetruecolor( $iWidth, $iHeight );
// copy and resize part of an image with resampling
imagecopyresampled($vDstImg, $vImg, 0, 0, 0, 0, $iWidth, $iHeight, $width, $height);
// define a result image filename
$sResultFileName = $sTempFileName . $sExt;
// output image to file
imagejpeg($vDstImg, $sResultFileName, $iJpgQuality);
#unlink($sTempFileName);
$user_id = $_SESSION['user_id'];
add_guest_picture($user_id, $sResultFileName);
// return $sResultFileName;
}
}
}
else {
foreach( $files as $name => $file ){
fetchImages($file, $images, $name);
}
}
}
?>
Ok issue resolved!
Apparently mime_content_type was not support by my host. after removing error suppression recommended by Musa I could catch the error.
I asked for my host to enable my mime php handling and now everything works.
Cheers.

How to display image on codeigniter that is stored in oracle database as BLOB type?

I am trying to display an image that is stored in oracle DB as BLOB data-type. this is my MODEL code
function viewblobData() {
$user = $this->session->userdata('user_logged_in');
$returnLobValue = '';
if (!empty($user)) {
$conn = $this->db->conn_id;
$sql = "SELECT * FROM OP_REG_IMAGE WHERE REG_NO = '$user'";
$stmt = oci_parse($conn, $sql);
oci_execute($stmt)
or die("Unable to execute query<br/>");
while ($row = oci_fetch_assoc($stmt)) {
$returnLobValue = $row['PAT_IMAGE']->load();
header("Content-type: image/jpg");
}
}
return $returnLobValue;
}
and this is for display at view
<?php echo $this->MY_MODEL->viewblobData(); ?>
But its shows "the image http://localhost/..... cannot be displayed because it contains errors"
if I remove the line header("Content-type: image/jpg"); then it shows like below whole page:
�M�t9UYG�G��d���~��5 �V�W��jժ�I�P��l6;��Po�ߖ�]��o�_���v��]o7{���Xr?_� ��bp��F3�s>ߙ�K)��f_�w��9����Z#���i�:�V�Y�h�=�����o���{��px=����o��fk���:>����~u�=��w��~9������y�]^����ٹ_���
Can anyone help?
You can use the image libraries:- e.g
$img = imagecreatefromstring($row['PAT_IMAGE']);
if ($img !== false) {
$image_new_name = 'sig_' . time() . '.png';
$image_path = 'upload/' . $image_new_name;
$image_name = $ROOT_DIR . '/' . $image_path;
if (!file_exists($image_name)) {
imagepng($img, $image_name);
imagedestroy($img);
} else {
$image_new_name = 'new_' . $image_new_name;
$image_path = 'upload/new_' . $image_new_name;
$image_name = $ROOT_DIR . '/' . $image_path;
imagepng($img, $image_name);
imagedestroy($img);
}
This code will generate image from your data to the provided dir. then use that image to display. enjoy. :)

How to automatically resize uploaded photo in PHP?

How to auto resize the image uploaded to this foder: 'assets/media/':
<?php defined('SYSPATH') OR die('No direct access allowed.');
class Uploader_Controller extends Controller_Core {
public function bulkUpload() {
Kohana::log('debug', 'Start to upload');
$files = Validation::factory($_FILES)
->add_rules('picture', 'upload::valid', 'upload::required', 'upload::type[gif,jpg,png,jpeg]', 'upload::size[10M]');
Kohana::log('debug', 'Start to validate');
if ($files->validate()) {
Kohana::log('debug', 'validate passed');
$filename = upload::save('picture');
$thumbSize = Kohana::config('upload.thumb_size');
Image::factory($filename)
->resize($thumbSize[0], $thumbSize[1], Image::WIDTH)
->save(DOCROOT . 'assets/media/thumbs/' . basename($filename));
$partName = explode('/', $filename);
$picture = $partName[count($partName) - 1];
$data['name'] = '';
$data['picture'] = $picture;
$data['category_id'] = $this->input->post('category_id', 0);
$data['description'] = '';
;
$data['user_id'] = $this->input->post('user_id', 0);
$pictureModel = new Picture_Model();
try {
$photo = $pictureModel->savePicture($data);
echo url::site('assets/media/' . $picture);
} catch (Exception $e) {
}
}
}
}
i have add this line but still not working:
$filename->resizeToWidth(300);
You are not using the Kohana image and upload library properly. The docs have some examples on how to use the Kohana image upload and resize library:
Upload and resize
Cropping Profile Images
Docs on how to use the image library
You can resize and save an image with to following code:
Image::factory($filename)
->resize(300, NULL, Image::AUTO)
->save($your_save_path);

Categories