Displaying BLOB image from Mysql database into dynamic div in html

前端 未结 1 916
抹茶落季
抹茶落季 2020-12-11 10:28

I have a BLOB image that is stored when the user submits an advert form, they have the choice of uploading one image. The image is stored in the database with the other info

相关标签:
1条回答
  • 2020-12-11 10:44

    1) Base64 option

    Work with a single line, image/png for a png image and image/jpeg for a jpg one :

    echo '<img src="data:image/png;base64,'.base64_encode($blob).'"/>';
    

    example :

    <div style="background-color:black; text-align:center; padding: 5px;">
      <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAwBAMAAACh2TSJAAAALVBMVEUAAADtNTX////3n5/+9fX719f7zMz5tLTzfHzuQED//f31jY3ybGzxXV3wVFRaxp+rAAAAAXRSTlMAQObYZgAAALVJREFUOMut0rENAjEQRNHdC4kY0QBaAQUQX0QAFSAKIKQEKiAA6VqgIkriApuV1x7pQPz0aWwHljLMpZ0CRDBGoXmeghGYKFJsUo90giAImCgV5OJF+oOgKE48MlGgs2VLBIunWesw0a1ZHqF82c7GmmIfUSpgotOly29DFPFJFDEhkgIT/V5mZuvj6XofKrHU6vyI4u37IYi36aN4h5tL7PJyif1dvCgEpapzISbCTEj5R78BZq5A5Ldh2XYAAAAASUVORK5CYII">
    </div>


    2) Dedicated page

    With many big picture on the same page, the base64 may be not the good choice

    Base64 is cool, but a bit heavy (usually around twice as the binary value encoded) and can't be cached by the browser as it's a part of the page, and not a page by itself (like a picture).

    In this case, the best is to use a specific php page to display your picture :

    On the main page use instead of base 64 : echo '<img src="image.php?id='.$id.'"/>'; with the id of the line you want the image.

    On your image.php, for the basic you should use this :

    // << include the $pdo here
    $query = $pdo->prepare("SELECT `content` FROM `adsubm` WHERE `id` = :id" );
    $query->execute(array(':id'=>$_GET['id']));
    $data = $query->fetch();
    
    if(empty($data)))
        header("HTTP/1.0 404 Not Found");
    else {
        header('Content-type: image/jpeg');
        echo $data['content'];
    }
    
    0 讨论(0)
提交回复
热议问题