我使用jquery将数据发布到控制器函数,该函数对位于服务器上的图像进行水印并动态地将其发回。水印功能在我不使用动态输出时起作用,但是当我这样做时,只返回一个空白图像,周围有一个1像素的灰色边框。
返回的图像已正确命名,并且已应用正确的图像类型标题。这是网络检查员返回的gobble-de-gook的第一行:
ÿØÿàJFIFÿþ;CREATOR: gd-jpeg v1.0 (using IJG JPEG v90), quality = 90
任何可以实现这一目标的替代方法都会受到赞赏,现在已经花了好几天才取得成功。如果可能的话,我更愿意保持服务器上的图像不受影响。
爪哇:
$('#body').on('click', '#get_file', function(ev)
{
ev.preventDefault();
var type = 'file';
var uid = $('#file_select').val();
var v1 = retD['res'][0].v1;
var v2 = retD['res'][0].v2;
var v3 = retD['res'][0].v3;
var v4 = retD['res'][0].v4;
$.ajax({
type: 'POST',
url: '<?php echo site_url("Home_controller/drawInfo") ?>',
data: {v1:v1, v2:v2, v3:v3, v4:v4},
dataType: 'html',
success: function(img)
{
$("#i").attr("src", img);
}
});
});
控制器:
function drawInfo()
{
$v1 = $_POST['v1'];
$v2 = $_POST['v2'];
$v3 = $_POST['v3'];
$v4 = $_POST['v4'];
$config['image_library'] = 'gd2';
$config['source_image'] = './img/Test_image.jpg';
$config['wm_text'] = 'v1: ' . $v1 . ' v2: ' . $v2 . ' v3: ' . $v3 . ' v4: ' . $v4;
$config['wm_type'] = 'text';
$config['dynamic_output'] = true;
$config['wm_font_color'] = 'ff0000';
$config['wm_font_path'] = './system/fonts/texb.ttf';
$config['wm_vrt_alignment'] = 'bottom';
$config['wm_hor_alignment'] = 'center';
$config['wm_padding'] = '20';
$this->image_lib->initialize($config);
if(!$this->image_lib->watermark())
{
echo $this->image_lib->display_errors();
}
}
答案 0 :(得分:1)
从控制器返回图像二进制数据,但是在Javascript中你想用它作为img元素的'src'属性。
在控制器中,您应该使用新生成的图像的src返回 设置路径并将权限设置为将生成图像的文件夹时,请务必小心(它应该由apache写入)。
控制器:
function drawInfo()
{
$return = array(
'src' => '',
'error' => '',
);
$v1 = $_POST['v1'];
$v2 = $_POST['v2'];
$v3 = $_POST['v3'];
$v4 = $_POST['v4'];
$config['image_library'] = 'gd2';
// set image path
$config['source_image'] = FCPATH . 'img/Test_image.jpg';
// this image will be watermarked (path should be writable by apache!!!)
$config['new_image'] = FCPATH . 'img/Test_image_new.jpg';
$config['wm_text'] = 'v1: ' . $v1 . ' v2: ' . $v2 . ' v3: ' . $v3 . ' v4: ' . $v4;
$config['wm_type'] = 'text';
// to false to save image to file instead of print it (you can leave this setting because the false is the default value)
$config['dynamic_output'] = false;
$config['wm_font_color'] = 'ff0000';
// set the proper path!!
$config['wm_font_path'] = FCPATH . 'system/fonts/texb.ttf';
$config['wm_vrt_alignment'] = 'bottom';
$config['wm_hor_alignment'] = 'center';
$config['wm_padding'] = '20';
$this->image_lib->initialize($config);
if(!$this->image_lib->watermark())
{
$return['error'] = $this->image_lib->display_errors();
}
else
{
// generate the URL of the new watermarked image (modify to your needs)
$return['src'] = base_url() .'/'. $config['new_image'];
}
echo json_encode($return);
}
JavaScript的:
$.ajax({
type: 'POST',
url: '<?php echo site_url("Home_controller/drawInfo") ?>',
data: {v1:v1, v2:v2, v3:v3, v4:v4},
dataType: 'html',
success: function(response)
{
if(response.error)
{
alert(response.error);
}
else
{
$("#i").attr("src", response.src);
}
}
});