Insert picture with Blob in database


I don’t know to insert picture in database with a blob.

Can you help me?


Or have you another solution for my problem ?

A picture is just data. You can save it the same as any other data. What have you tried, and what isn’t working about it?

I would advise against doing this tho as it will make your database really bulky and make it a big hassle to backup your data.
Instead, I’d advise to just upload it to your webroot and add a reference (to it’s public path) in the database instead.

So let’s say you upload the file to webroot/img/uploads/whatever.webp.
Then you just store whatever.webp in your database (as TEXT or VARCHAR(255), whatever bakes your cake).

Then when you want to display it, you just do something like this:

// src/Controller/FooController.php
public function view() {
  $image = get_image_reference_from_database(); // returns either reference text or null
  $this->set('image', !empty($image) ? $image : 'fallback.webp');
<img src="/img/uploads/<?= h($image); ?>" class="my-class" alt="Image Alt" referrerpolicy="no-referrer">

I concur with FinlayDaG33k I have a system that store images in the database and its a nightmare. Now what I do is break the images down to months and store the whole path. Much easier.

However I hate when an answer doesnt answer the question so code from a cakephp2 app that I wrote many years ago would be similar now in cakephp4.

$photo = $this->request->data['User']['profile_picture'];

 $fileData = fread(fopen($photo['tmp_name'], 'r'), $photo['size']);
 $this->request->data['User']['photo'] = $this->create_profile_photo($fileData);

$this->User->save($this->request->data, true, $fieldlist)) {

    function create_profile_photo($photo_stream){
            $desired_width = 140;
            $desired_height = 180;
            $im = imagecreatefromstring($photo_stream);
            $new = imagecreatetruecolor($desired_width, $desired_height);
            $x = imagesx($im);
            $y = imagesy($im);
            imagecopyresampled($new, $im, 0, 0, 0, 0, $desired_width, $desired_height, $x, $y);
            $tmpFilePath = APP.'tmp/0000.jpg';
            imagejpeg($new, $tmpFilePath, 85);  
            $photo = file_get_contents($tmpFilePath);
            return $photo;

    public function get_profile_image($id=null){
        $this->autoRender = false;
        if (!$this->User->exists($id)) {
            throw new NotFoundException(__('Invalid user'));
        $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
        $user = $this->User->find('first', $options);
        $photo = null;
        if (isset($user['User']['photo'])) {
            $photo = $user['User']['photo'];
        } else {
            $photo = file_get_contents(APP.'webroot/img/user.jpg');
        echo $photo;