Image conversion with PHP

Asked

Viewed 28 times

0

It’s my first day with php and I’m doing a select that returns an image, as I do to render this image. Follow my select and the return of the image:

class CooperMaisController {

public function getItens(){
    $connect = OpenConnection();
    $query = ibase_query($connect, " select * from CAD_PROD_PONTUACAO_RESGATE PP left join CAD_PRODUTOS CP on CP.EMPRESA = PP.EMPRESA and  CP.CODIGO = PP.PRODUTO ");

    if ($query){                
        $pagamentos = array();          
        while ($row = ibase_fetch_object($query)){              
            $pagamento = new coopermais();
            $pagamento->setCodigo($row->CODIGO);
            $pagamento->setPontuacao($row->PONTUACAO);
            $pagamento->setNome($row->NOME);
            $pagamento->setFoto($row->FOTO);                
            $pagamentos[] = $pagamento;         
        }           
        return $pagamentos;
    } else {
        return "Erro: ".ibase_errmsg();
    }

    unset($row);
    unset($query);
    ibase_close($connect);
   }    
}

When I give a var_dump in the image I visualize this: inserir a descrição da imagem aqui

I’m getting used to Javascript and Node where saved the converted image in the database as base 64 (it was a huge string), now with php when saving the image appears this:

inserir a descrição da imagem aqui

When I look at the XML the image is rendered.

  • The field is BLOB with the sub_type as binary?

  • Yes a Binary blob field with size 80, I can visualize the image perfectly in the bank.

  • 80 is very little, will the image not truncated?

1 answer

0

I’m not quite sure, but I think I have to convert to VARCHAR

SELECT *, CAST(SUBSTRING(blob1 FROM 1 FOR 80) AS VARCHAR(80)) AS IMAGECHAR

And would pass like this:

$pagamento->setFoto($row->IMAGECHAR);

However if you are going to display in an HTML you may have to use data URI Scheme, ie the image will have to be converted to Base64, to use the data URI it is necessary to know the image mimetype will be necessary to activate in the PHP of your server the extension file_info, the code should look like this:

a generic example just to understand:

function mimeType($data)
{
    $mimetype = false;

    if (class_exists('finfo')) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimetype = finfo_buffer($finfo, $data);
        finfo_close($finfo);
    }

    return $mimetype ? $mimetype : 'imagem/jpeg'; //jpeg será um fallback pra facilitar
}

...

while ($row = ibase_fetch_object($query)){              
    $imagem = base64_encode($row->IMAGECHAR);

    echo '<img src="data:image/jpeg;base64,', base64_encode($imagem),'">';
}

...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.