0
I am developing a system that uses Mysql as a database and Mongo BD for image storage. The problem is that the images loading is very slow. OBS: I am using Laravel 5.2.
Function that loads image:
$db = new Conection("imagens");
$image = $db->find((int) $id);
if ($image != null) {
$imageFile = $image->getBytes();
return response($imageFile)->header('Content-Type', $image->file['MIME']);
}
return 'Erro';
Conection class:
<?php
namespace App\Bigdata;
use \MongoDB;
class Conection {
private $c = null;
public function __construct($database="images"){
$this->c = new \MongoDB(new \MongoClient(), $database);
$this->grifs = $this->c->getGridFS();
}
public function find($id){
return $this->grifs->findOne(array("_id" => $id));
}
private function getMimeType( $filename ) {
$realpath = realpath( $filename );
if ( $realpath
&& function_exists( 'finfo_file' )
&& function_exists( 'finfo_open' )
&& defined( 'FILEINFO_MIME_TYPE' )
) {
// Use the Fileinfo PECL extension (PHP 5.3+)
return finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $realpath );
}
if ( function_exists( 'mime_content_type' ) ) {
// Deprecated in PHP 5.3
return mime_content_type( $realpath );
}
return false;
}
public function saveFile($file, $id, $mime=null){
try {
$name = explode("/", $file);
if (count($name) <= 1)
$name = explode("\\", $file);
$name = $name[count($name) - 1];
$this->grifs->storeFile($file, array("_id" => $id, "filename" => $name, "MIME" => ($mime == null ? $this->getMimeType($file) : $mime)));
}catch (\MongoGridFSException $e){
return false;
}
return true;
}
public function saveBytes($bytes, $name, $id, $mime){
try {
$this->grifs->storeBytes($bytes, array("_id" => $id, "filename" => $name, "MIME" => $mime));
}catch (\MongoGridFSException $e){
return false;
}
return true;
}
public function updateFile($file, $id, $mime=null){
try {
$this->grifs->remove(['_id'=> (int) $id]);
$name = explode("/", $file);
if (count($name) <= 1)
$name = explode("\\", $file);
$name = $name[count($name) - 1];
$this->grifs->storeFile($file, array("_id" => $id, "filename" => $name, "MIME" => ($mime == null ? $this->getMimeType($file) : $mime)));
}catch (\MongoGridFSException $e){
return false;
}
return true;
}
}
Have you checked the image size? This factor interferes, heavier image takes longer to load.
– Guilherme Lautert
You have checked in which step your code is slow?
– user3603
Really it was the size of the image, I was downloading in HD and I wanted in 250px, I resized the image and solved my problem, thank you very much.
– Pedro Soares