这是我的控制者:
public function actionFind($id, $c, $t, $width = false, $height = false)
{
$image = \app\models\Picture::finding($id, $c, $t, $width, $height);
\Yii::$app->response->format = yii\web\Response::FORMAT_RAW;
\Yii::$app->response->headers->add('content-type', 'image/jpeg');
\Yii::$app->response->data = file_get_contents($image);
return \Yii::$app->response;
}
这是我的模特:
public static function finding($id, $c, $t, $width = false, $height = false)
{
$query = new Query;
// compose the query
$query->select('*')
->from($t)
->where("Active=1 AND Code = $id")
->limit(1);
$query->orderBy('Code desc');
// build and execute the query
$rows = $query->all();
// alternatively, you can create DB command and execute it
$command = $query->createCommand();
// $command->sql returns the actual SQL
$rows = $command->queryAll();
if (isset($rows[0]["$c"]))
{
return $image = "data:image/jpeg;base64," . base64_encode($rows[0]["$c"]);
}
}
这是我的错误:
cannot be displayed because it contains an error
我的图片保存在数据库中!!
图片:longblob
在另一个带数据库的项目中,这段代码运行正确:
header("Content-Type: image/jpeg");
if (strlen($image) == 0 || $id == "")
{
if (!$w)
$w = $w1;
if (!$h)
$h = $h1;
if (!$w)
$w = 120;
if (!$h)
$h = 140;
$dst = imagecreatetruecolor($w, $h);
$gray = imagecolorallocate($dst, 255, 255, 255);
imagefill($dst, 1, 1, $gray);
if ($q)
imagejpeg($dst, NULL, $q);
else
imagejpeg($dst);
}
答案 0 :(得分:0)
正如我在评论中提到的,我使用你的代码来显示图像,这是一个例子:
/**
* Displays homepage.
*
* @return string
*/
public function actionIndex()
{
\Yii::$app->response->format = yii\web\Response::FORMAT_RAW;
\Yii::$app->response->headers->add('content-type', 'image/png');
\Yii::$app->response->data = file_get_contents("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4
9TXL0Y4OHwAAAABJRU5ErkJggg==");
return \Yii::$app->response;
}
尽管数据保存在数据库中,但当您检索数据时,您只需将其编码为64个基本字符串,这类似于我使用的硬编码字符串。再次,检查您的数据。
注意:我还将图片/ jpeg标头与png图片一起使用,虽然不行,但不推荐