从SQL数据库显示图像

时间:2010-01-22 07:27:45

标签: php sql-server-2008 image-processing

我最近一直致力于静态内容处理程序项目,这让我很难受。我无法以前所未有的方式将图像显示在浏览器中。图像是正确的,这是不可能的,因为我的代码几乎保持不变。

ob_start();

function ImageExistsSql($img)
{
 $rows = mssql_num_rows(mssql_query("SELECT id FROM Static_Image WHERE name = N'{$img}'"));
 if($rows > 0)
 {
  return true;
 }
 else
 {
  return false;
 }

}

function ImageExistsFile($img)
{
 if(!file_exists("images/".$img))
 {
  return false;
 }
 else
 {
  return true;
 }
}

function CreateImageFile($img)
{
 if(!ImageExistsFile($img))
 {
  $b =& new hex2bin;
  $data = mssql_fetch_row(mssql_query("SELECT data FROM Static_Image WHERE name = N'{$img}'"));
  $file = fopen("images/".$img, 'a+');
  fwrite($file, $b->convert($data));
  fclose($file);
 }

}

function GetExtension($img)
{
 return mssql_fetch_row(mssql_query("SELECT extension FROM Static_Image WHERE name = N'{$img}'"));
}

function WriteImageDataToScreen($img)
{
 $r = mssql_fetch_row(mssql_query("SELECT data FROM Static_Image WHERE name = N'{$img}'"));
 $d = str_split($r);

 for($i = 0; $i < strlen($r); $i++)
 {
  echo($d[$i]);
 }
}

function ContentHeader($img)
{
 $ext = GetExtension($img);
 switch($ext[0])
 {
  case "png":
  case ".png":
   header("Content-type: image/png");
   break;

  case "gif":
  case ".gif":
   header("Content-type: image/gif");
   break;

  case "jpg":
  case "jpeg":
  case ".jpg":
  case ".jpeg":
   header("Content-type: image/jpeg");
   break;

  default:
   die("[STATIC HANDLER] Extension: {$ext} not found");
   break;

 }
}

if(isset($_GET['i']))
{
 $imgf = $_GET['i'];
 $ext = GetExtension($imgf);

 if(ImageExistsSql($imgf))
 {
  if(ImageExistsFile($imgf))
  {
   ContentHeader($imgf);
   //$fn = fopen("images/".$imgf, 'rb');
   //fpassthru($fn);
                    // fpassthru isn't working anymore, used to work.
   WriteImageDataToScreen($imgf);
  }
  else
  {
   CreateImageFile($imgf);
   header("Location: {$_SERVER['REQUEST_URI']}");
  }
 }
 else
 {
  die("[STATIC HANDLER] IMAGE NON EXISTANT");
 }
}
else
{
 die("[STATIC HANDLER] FAILED TO PROCESS FILE");
} 

ob_end_flush();

表Static_Image如下

CREATE TABLE [dbo].[Static_Image](
 [id] [int] IDENTITY(1,1) NOT NULL,
 [name] [varchar](50) NOT NULL,
 [extension] [varchar](6) NULL,
 [dateadded] [date] NULL,
 [data] [image] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

使用了数据列,但直到最近才将其用作将其扩展到多个服务器上的方法。

1 个答案:

答案 0 :(得分:0)

$data = mssql_fetch_row(mssql_query("SELECT data FROM Static_Image WHERE name = N'{$img}'"));
$file = fopen("images/".$img, 'a+');
fwrite($file, $b->convert($data));

应该是$b->convert($data[0])吗?

请注意,将图像专门存储在磁盘上通常更容易,只需将路径名保留在db ...