从 mySQL 的 base64_decode 生成缩略图

发布于 2025-01-05 04:20:17 字数 4832 浏览 6 评论 0原文

我正在尝试编写从 mySQL 数据库的 base64_decode 生成缩略图的代码,但问题是为什么它说文件不是有效的 JPEG,我确信源文件是纯 JPG 文件格式。那么我无法解决:(

源文件(BASE64_ENCODE): http://pastebin.com/wFBcd79B

view/Helper 文件夹中的 image.php 代码:

<?php
class ImageHelper extends Helper {
    var $helpers = array('Html');
    var $cacheDir = 'imagecache';

    function getfile($i) {

        preg_match_all("/data:(.*);base64,/", $i, $temp_imagetype);

        $imagetype = $temp_imagetype[1][0];

        $image = base64_decode(preg_replace("/data.*base64,/","",$i));

        //echo $image;

        ob_start();

        //header("Content-type: ".$imagetype);
        header('Content-Type: image/jpeg');
        print($image);

        $data = ob_get_clean();

        //file_put_contents($this->webroot.'tmp/temp.jpg', 'test' );

        file_put_contents(ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.'tmp/temp.jpg', $data );


        //return ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.'tmp/temp2.jpg';
        //return 'temp2.jpg';
        return 'temp.jpg';
    //}
    }


    //source from: http://bakery.cakephp.org/articles/hundleyj/2007/02/16/image-resize-helper and modified for base64_decode
    function resize($path, $width, $height, $aspect = true, $htmlAttributes = array(), $return = false) {
        $types = array(1 => "gif", "jpeg", "png", "swf", "psd", "wbmp"); // used to determine image type 

        //$fullpath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.$this->themeWeb.IMAGES_URL;

        $fullpath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.IMAGES_URL;

        $temppath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.'tmp/';


        //$formImage = imagecreatefromstring(base64_decode(preg_replace("/data.*base64,/","",$path)));

        //$url = $formImage;

        //$path = $this->getfile($path);

        $url = $temppath.$path;

        //$url = preg_replace("/data.*base64,/","",$path);

        //$url = base64_decode($url);

        if (!($size = getimagesize($url)))
            return; // image doesn't exist

        if ($aspect) { // adjust to aspect.
            if (($size[1]/$height) > ($size[0]/$width))  // $size[0]:width, [1]:height, [2]:type
                $width = ceil(($size[0]/$size[1]) * $height);
            else
                $height = ceil($width / ($size[0]/$size[1]));
        }

        $relfile = $this->cacheDir.'/'.$width.'x'.$height.'_'.basename($path); // relative file
        $cachefile = $fullpath.$this->cacheDir.DS.$width.'x'.$height.'_'.basename($path);  // location on server

        if (file_exists($cachefile)) {
        $csize = getimagesize($cachefile);
        $cached = ($csize[0] == $width && $csize[1] == $height); // image is cached
        if (@filemtime($cachefile) < @filemtime($url)) // check if up to date
            $cached = false;
        } else {
            $cached = false;
        }

        if (!$cached) {
            $resize = ($size[0] > $width || $size[1] > $height) || ($size[0] < $width || $size[1] < $height);
        } else {
            $resize = false;
        }

        if ($resize) {
            $image = call_user_func('imagecreatefrom'.$types[$size[2]], $url);
            if (function_exists("imagecreatetruecolor") && ($temp = imagecreatetruecolor ($width, $height))) {
                imagecopyresampled ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
            } else {
                $temp = imagecreate ($width, $height);
                imagecopyresized ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
            }
                call_user_func("image".$types[$size[2]], $temp, $cachefile);
                imagedestroy ($image);
                imagedestroy ($temp);
        }
        return $this->output(sprintf($this->Html->image($relfile,$htmlAttributes)));
    }
}
?>

'index.php' 中查看文件夹代码:

<?php
    foreach ($products as $product):
        echo $this->Image->resize($this->Image->getfile($product['Product']['image1']), 120, 120, false); 
    endforeach;
    ?>

输出是错误日志:

> Warning (2): imagecreatefromjpeg() [function.imagecreatefromjpeg]:
> gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file 
> [APP/View/Helper/image.php, line 86] 
> Warning (2): imagecreatefromjpeg() [function.imagecreatefromjpeg]:
> '/Users/user/Sites/mycakeapp/app/webroot/tmp/temp.jpg' is not a valid
> JPEG file [APP/View/Helper/image.php, line 86] 
> Warning (2): imagecopyresampled() expects parameter 2 to be resource, boolean given
> [APP/View/Helper/image.php, line 88] 
> Warning (2): imagedestroy() expects parameter 1 to be resource, boolean given
> [APP/View/Helper/image.php, line 94]

Im trying to make code for generate thumbnail from base64_decode from mySQL Database but problem is why it said file is not valid JPEG im sure that source file is pure JPG file format. then I can't solve :(

source file (BASE64_ENCODE):
http://pastebin.com/wFBcd79B

image.php in view/Helper folder code:

<?php
class ImageHelper extends Helper {
    var $helpers = array('Html');
    var $cacheDir = 'imagecache';

    function getfile($i) {

        preg_match_all("/data:(.*);base64,/", $i, $temp_imagetype);

        $imagetype = $temp_imagetype[1][0];

        $image = base64_decode(preg_replace("/data.*base64,/","",$i));

        //echo $image;

        ob_start();

        //header("Content-type: ".$imagetype);
        header('Content-Type: image/jpeg');
        print($image);

        $data = ob_get_clean();

        //file_put_contents($this->webroot.'tmp/temp.jpg', 'test' );

        file_put_contents(ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.'tmp/temp.jpg', $data );


        //return ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.'tmp/temp2.jpg';
        //return 'temp2.jpg';
        return 'temp.jpg';
    //}
    }


    //source from: http://bakery.cakephp.org/articles/hundleyj/2007/02/16/image-resize-helper and modified for base64_decode
    function resize($path, $width, $height, $aspect = true, $htmlAttributes = array(), $return = false) {
        $types = array(1 => "gif", "jpeg", "png", "swf", "psd", "wbmp"); // used to determine image type 

        //$fullpath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.$this->themeWeb.IMAGES_URL;

        $fullpath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.IMAGES_URL;

        $temppath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.'tmp/';


        //$formImage = imagecreatefromstring(base64_decode(preg_replace("/data.*base64,/","",$path)));

        //$url = $formImage;

        //$path = $this->getfile($path);

        $url = $temppath.$path;

        //$url = preg_replace("/data.*base64,/","",$path);

        //$url = base64_decode($url);

        if (!($size = getimagesize($url)))
            return; // image doesn't exist

        if ($aspect) { // adjust to aspect.
            if (($size[1]/$height) > ($size[0]/$width))  // $size[0]:width, [1]:height, [2]:type
                $width = ceil(($size[0]/$size[1]) * $height);
            else
                $height = ceil($width / ($size[0]/$size[1]));
        }

        $relfile = $this->cacheDir.'/'.$width.'x'.$height.'_'.basename($path); // relative file
        $cachefile = $fullpath.$this->cacheDir.DS.$width.'x'.$height.'_'.basename($path);  // location on server

        if (file_exists($cachefile)) {
        $csize = getimagesize($cachefile);
        $cached = ($csize[0] == $width && $csize[1] == $height); // image is cached
        if (@filemtime($cachefile) < @filemtime($url)) // check if up to date
            $cached = false;
        } else {
            $cached = false;
        }

        if (!$cached) {
            $resize = ($size[0] > $width || $size[1] > $height) || ($size[0] < $width || $size[1] < $height);
        } else {
            $resize = false;
        }

        if ($resize) {
            $image = call_user_func('imagecreatefrom'.$types[$size[2]], $url);
            if (function_exists("imagecreatetruecolor") && ($temp = imagecreatetruecolor ($width, $height))) {
                imagecopyresampled ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
            } else {
                $temp = imagecreate ($width, $height);
                imagecopyresized ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
            }
                call_user_func("image".$types[$size[2]], $temp, $cachefile);
                imagedestroy ($image);
                imagedestroy ($temp);
        }
        return $this->output(sprintf($this->Html->image($relfile,$htmlAttributes)));
    }
}
?>

'index.php' in view folder code:

<?php
    foreach ($products as $product):
        echo $this->Image->resize($this->Image->getfile($product['Product']['image1']), 120, 120, false); 
    endforeach;
    ?>

Output is error log:

> Warning (2): imagecreatefromjpeg() [function.imagecreatefromjpeg]:
> gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file 
> [APP/View/Helper/image.php, line 86] 
> Warning (2): imagecreatefromjpeg() [function.imagecreatefromjpeg]:
> '/Users/user/Sites/mycakeapp/app/webroot/tmp/temp.jpg' is not a valid
> JPEG file [APP/View/Helper/image.php, line 86] 
> Warning (2): imagecopyresampled() expects parameter 2 to be resource, boolean given
> [APP/View/Helper/image.php, line 88] 
> Warning (2): imagedestroy() expects parameter 1 to be resource, boolean given
> [APP/View/Helper/image.php, line 94]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

睫毛上残留的泪 2025-01-12 04:20:17

您链接到的 Base64 编码数据的长度正好是 216 (65536) 字节。这个数字太圆了,不可能是巧合。

数据库列是否定义为 TEXT?将其转换为更大的内容,例如 MEDIUMTEXTLONGTEXT

将图像存储在文件系统中会更有意义。虽然数据库可以存储文件等任意数据,但存在一些限制使其不切实际:大量数据必须通过网络从数据库服务器传输到应用程序,因此存在性能问题。巨大的数据库需要更长的时间来备份。并且您可能需要修改数据库设置:

BLOB 或 TEXT 对象的最大大小由其类型决定,但实际可以在客户端和服务器之间传输的最大值由可用内存量和通信缓冲区的大小决定。您可以通过更改 max_allowed_pa​​cket 变量 的值来更改消息缓冲区大小,但您必须对服务器和客户端程序执行此操作。

http://dev.mysql.com/doc/refman/5.0/en /blob.html

The base64 encoded data you link to is exactly 2¹⁶ (65536) bytes long. That number is just too round to be a coincidence.

Is the database column defined as TEXT? Convert it to something bigger, like MEDIUMTEXT or LONGTEXT.

It would make more sense to store images in the file system. While databases can store arbitrary data like files, there are limitations that make it impractical: A larger amount of data has to be transferred from the database server to the application over a network so there's a performance issue. Huge databases take longer to back up. And you may need to modify database settings:

The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers. You can change the message buffer size by changing the value of the max_allowed_packet variable, but you must do so for both the server and your client program.

http://dev.mysql.com/doc/refman/5.0/en/blob.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文