【问题标题】:php Rotating image and resavingphp 旋转图像并重新保存
【发布时间】:2014-03-18 19:42:23
【问题描述】:

所以我上传了一张图片,我想做的是让用户旋转它,接收该值并旋转图片并用新图片替换原始图片。

所以我有一个按钮:

<a href="#" data-id="2" class="btn btn-primary">Rotate</a>

在我的 js 文件中:

$('.rotate').on('click', function(e){
   e.preventDefault();
   if(rotate < 360)
    rotate = rotate +90;
   else
    rotate = 0;

   var id = $(this).data('id');

   $('.img-container img').attr('style', '-webkit-transform: rotate(' + rotate + 'deg)');

   $.ajax({
       type: "POST",
       url: "functions/post",
       data: { rotate: rotate, id: id }
   });

});

在“函数/帖子”内部:

$degrees = $_POST['rotate'];
$postid = $_POST['postid'];

//user the postid to get the imagefilepath from db
$filename = '../img/uploads/' . $post->getimagepath();

// Content type
header('Content-type: image/jpeg');

// Load
$source = imagecreatefromjpeg($filename);

// Rotate
$rotate = imagerotate($source, $degrees, 0);

// Output
imagejpeg($rotate);

list($width, $height) = getimagesize($rotate);
$newImage = imagecreatetruecolor($width, $height);
imagecopyresampled($newImage, $source, 0, 0, 0, 0, $width, $height, imagesx($source), imagesy($source));
imagejpeg($newImage, realpath('../img/uploads/' . $post->getimagepath()));
// Free the memory
imagedestroy($source);
imagedestroy($rotate);
imagedestroy($newImage);

但它不保存旋转的文件.. :( 这段代码是我通过so和google搜索得到的,但似乎还不能让它对我有用。这段代码都不是一成不变的,所以任何需要改变的地方,只要它可以工作,那么一切都很好,非常感谢。

【问题讨论】:

  • 你检查过$post-&gt;getimagepath()吗?
  • 另外,你为什么将标题设置为image/jpeg
  • 是的 $post->getimagepath 返回文件名和我认为我必须这样做的标题 idk..

标签: php image rotation


【解决方案1】:

您不是保存旋转后的图像,而是重新保存原始图像。

试试这个:

$degrees = $_POST['rotate'];
$postid = $_POST['postid'];

//user the postid to get the imagefilepath from db
$filename = '../img/uploads/' . $post->getimagepath();

// Content type
header('Content-type: image/jpeg');

// Load
$source = imagecreatefromjpeg($filename);

// Rotate
$rotate = imagerotate($source, $degrees, 0);

imagejpeg($rotate, realpath('../img/uploads/' . $post->getimagepath()));
// Free the memory
imagedestroy($source);
imagedestroy($rotate);

(未测试)但你明白了。

【讨论】:

  • 是的,我也看到了,但由于某种原因,它仍然没有保存。
  • 就像我说的,它未经测试。玩弄它;)你可能已经接近了。
  • 它有效,但我必须使用 $_SERVER['DOCUMENT_ROOT'] 否则找不到它。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2012-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多