使用php (utf-8)从mssql检索图像数据


Retrieve image data from mssql with php (utf-8)

从php脚本(php 5.3.10-1在Ubuntu3.6上)我连接到一个MSSQL服务器,我想从图像字段类型检索图像数据。我想把它打印出来

我可以从MSSQL获得数据,但我不能打印/回显它作为一个有效的图像。我怎么打印/打印/保存它?

$db= new PDO('odbc:MYODBC', '***', '***');
$stmt = $db->prepare("USE database");
$stmt->execute();
$tsql = "SELECT image 
         FROM Pics 
         WHERE id = 12";
$stmt = $db->prepare($tsql);
$stmt->execute();
$stmt->bindColumn(1, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);
header("Content-Type: image/jpg");
echo($lob); //not an image: 424df630030000000000360000002800 ...
imagecreatefromstring($lob);  // Data is not in a recognized format ...
$lob = fopen('data://text/plain;base64,' . base64_encode($lob), 'r'); //Resource
fpassthru($lob); //not an image: 424df63003000000000036000000280000 ...

PHP脚本编码:UTF-8.

在/etc/freetds/freetds.conf

[MYODBC]
host = myhost.com
client charset = UTF-8
tds version = 7
在MSSQL服务器上使用sqlsrv,我可以使用以下命令:
$image = sqlsrv_get_field( $stmt, 0, 
                      SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY));
header("Content-Type: image/jpg");
fpassthru($image);

)

:

echo base64_decode($lob); //Not an image: γn­τΣ}4ΣM4ΣM4ί­4ΣM4ΫΝ4ΣM4s­...

尝试添加以下标题:

  • 附加
  • Content-Transfer-Encoding
  • 内容长度

PHP代码:

header('Content-Type: image/jpg');
header('Content-Disposition:attachment; filename="my_file.jpg"');// Set the filename to your needs
header('Content-Transfer-Encoding: binary');
header('Content-Length: 12345');// Replace 12345 with the actual size of the image in bytes

我最近遇到了一个类似的存储问题。事实证明,我在插入数据库表之前引用了我的二进制图像数据。因此,请确保您没有添加引号并将其转换为字符串-就像我不小心做的那样。

下面是在现有本地文件上完成的准备工作,以便将适当的数据存储到数据库中。此外,请确保您有可用的bin2hex()或获得该函数的替换版本。

function prepareImageDBString($filepath) {
    $out = 'null';
    $handle = @fopen($filepath, 'rb');
    if ($handle) {
        $content = @fread($handle, filesize($filepath));
        // bin2hex() PHP Version >= 5.4 Only!
        $content = bin2hex($content); 
        @fclose($handle);
        $out = "0x" . $content;
    }
    return $out;
}