如何旋转图像并保存图像
Posted
技术标签:
【中文标题】如何旋转图像并保存图像【英文标题】:How to rotate image and save the image 【发布时间】:2012-06-30 20:56:41 【问题描述】:在我的应用程序中,我在 div 中有一个图像,一个按钮。
当我使用 jquery 单击按钮时,我想旋转显示的图像并保存旋转后的图像。
我已经用过代码了:
http://code.google.com/p/jquery-rotate/
和jquery代码:
$(function() // doc ready
var rotation = 0; // variable to do rotation with
$("#img").click(function()
rotation = (rotation + 45) % 360; // the mod 360 probably isn't needed
$("#cropbox").rotate(rotation);
);
);
html代码:
<img src="demo_files/pool.jpg" id="cropbox" />
<input type="button" id="img" name="img" value="click" />
当我使用上面的代码时,有两个图像,一个是旧图像,另一个是旋转图像。
这里我想旋转相同的图像并只显示旋转后的图像。并将旋转后的图像保存在目录中。
如何使用 jquery 做到这一点? 如果使用 jquery 无法实现,那么我如何使用 php/ajax 来实现呢?
【问题讨论】:
您无法使用 javascript 保存数据。使用 AJAX 保存图像。 看到这篇文章9lessons.info/2011/08/ajax-image-upload-without-refreshing.html 我已经使用 ajax 上传了图片。现在我想旋转它吗? 试试这个:code.google.com/p/jqueryrotate/wiki/Examples 【参考方案1】://define image path
$filename="image.jpg";
// Load the image
$source = imagecreatefromjpeg($filename);
// Rotate
$rotate = imagerotate($source, $degrees, 0);
//and save it on your server...
imagejpeg($rotate, "myNEWimage.jpg");
看看:
imagerotate()
还有:
file_put_contents()
【讨论】:
你实际上需要使用imagepng()
来写文件,而不是file_put_contents()
。
谢谢。但我不能使用 file_put_contents() 保存旋转图像。我改用了函数 imagejpeg()。
使用 imagepng() 或 imagejpeg() 代替 file_put_contents()。
简单甜美【参考方案2】:
图像旋转:PNG 或 JPEG 取决于文件类型并保存在您的服务器上
// File and rotation
$rotateFilename = '/var/www/your_image.image_type'; // PATH
$degrees = 90;
$fileType = strtolower(substr('your_image.image_type', strrpos('your_image.image_type', '.') + 1));
if($fileType == 'png')
header('Content-type: image/png');
$source = imagecreatefrompng($rotateFilename);
$bgColor = imagecolorallocatealpha($source, 255, 255, 255, 127);
// Rotate
$rotate = imagerotate($source, $degrees, $bgColor);
imagesavealpha($rotate, true);
imagepng($rotate,$rotateFilename);
if($fileType == 'jpg' || $fileType == 'jpeg')
header('Content-type: image/jpeg');
$source = imagecreatefromjpeg($rotateFilename);
// Rotate
$rotate = imagerotate($source, $degrees, 0);
imagejpeg($rotate,$rotateFilename);
// Free the memory
imagedestroy($source);
imagedestroy($rotate);
对我有用,试试吧。
【讨论】:
哇,真是一个答案,非常好,我在 CI 中花了一整天的轮换任务,之后我得到了它。非常感谢 Ghanshyam【参考方案3】:<?php //image rotate code here
if(isset($_POST['save']))
$degrees=90;
$new_file=$sourceName;
$filename ="http://localhost/dostoom/files_user/1000/4/153.jpg";
$rotang = $degrees;
list($width, $height, $type, $attr) = getimagesize($filename);
$size = getimagesize($filename);
switch($size['mime'])
case 'image/jpeg':
$source =
imagecreatefromjpeg($filename);
$bgColor=imageColorAllocateAlpha($source, 0, 0,
0, 0);
$rotation = imagerotate($source,
$rotang,$bgColor);
imagealphablending($rotation, false);
imagesavealpha($rotation, true);
imagecreate($width,$height);
imagejpeg($rotation,$new_file);
chmod($filename, 0777);
break;
case 'image/png':
$source =
imagecreatefrompng($filename);
$bgColor=imageColorAllocateAlpha($source, 0, 0,
0, 0);
$rotation = imagerotate($source,
$rotang,$bgColor);
imagealphablending($rotation, false);
imagesavealpha($rotation, true);
imagecreate($width,$height);
imagepng($rotation,$new_file);
chmod($filename, 0777);
break;
case 'image/gif':
$source =
imagecreatefromgif($filename);
$bgColor=imageColorAllocateAlpha($source, 0, 0,
0, 0);
$rotation = imagerotate($source,
$rotang,$bgColor);
imagealphablending($rotation, false);
imagesavealpha($rotation, true);
imagecreate($width,$height);
imagegif($rotation,$new_file);
chmod($filename, 0777);
break;
case 'image/vnd.wap.wbmp':
$source =
imagecreatefromwbmp($filename);
$bgColor=imageColorAllocateAlpha($source, 0, 0,
0, 0);
$rotation = imagerotate($source,
$rotang,$bgColor);
imagealphablending($rotation, false);
imagesavealpha($rotation, true);
imagecreate($width,$height);
imagewbmp($rotation,$new_file);
chmod($filename, 0777);
break;
?>
【讨论】:
【参考方案4】:这将有助于旋转图像并将图像保存在任何角度图像中。例如,我们将图像旋转 180 度。我们可以将该图像(180 度)保存到我们的文件夹中。这里我们使用了画布。它对 ASP.NET 开发人员有帮助
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" id="CLoseToggle" onclick="CloseModal()">×</button>
<h4 class="modal-title">Image Preview</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 cr-img-box">
<asp:Image ID="CropImg" ImageUrl="" runat="server" class="north"/>
<canvas id="canvas"></canvas>
<input type="hidden" id="hfData" runat="server"/>
<input type="hidden" id="hdnCropImageFileLocation"/>
</div>
</div>
</div>
<div class="modal-footer">
<div style="text-align: center;">
<input type="button" id="btnRotate" class="btn btn-sm btn-info" value="Rotate"/>
<asp:Button ID="OKFinalSave" class="btn btn-sm btn-info" Text="Submit" runat="server"
OnClick="OKFinalSave_Click"/>
</div>
</div>
</div>
</div>
</div>
protected void OKFinalSave_Click(object sender, EventArgs e)
string
CropImageLocation = ConfigurationManager.AppSettings["CropFileLocation"].ToString();
CropImageLocation = CropImageLocation + DateTime.Now.ToString("yyyyMMdd") + "\\" + LoanNumber.Value;
string
a = CropImageLocation + "\\" + LoanNumber.Value + "_SIGN";
string
base64String = hfData.Value.Replace("data:image/png;base64,", string.Empty);
byte[]
bytes = Convert.FromBase64String(base64String);
string
filePath = a;
if (!Directory.Exists(CropImageLocation))
Directory.CreateDirectory(CropImageLocation);
if (File.Exists(a))
File.Delete(CropImageLocation + "\\" + LoanNumber.Value + "_SIGN");
System.IO.File.WriteAllBytes(CropImageLocation + "\\" + LoanNumber.Value + "_SIGN.jpeg", bytes);
SaveCropedPath(LoanNumber.Value, CropImageLocation + "\\" + LoanNumber.Value + "_SIGN.jpeg");
<script type = "text/javascript" >
var img = null, canvas = null;
$(function ()
$("#canvas").css("display", "none");
img = document.getElementById('CropImg');
canvas = document.getElementById('canvas');
if (!canvas || !canvas.getContext)
canvas.parentNode.removeChild(canvas);
else
//img.style.position = 'absolute';
//img.style.visibility = 'hidden';
RotateImage(0);
$('#btnRotate').click(function ()
$("#CropImg").css("display", "none");
$("#canvas").css("display", "block");
if (img.className == "north")
RotateImage(90);
img.className = "west";
else if (img.className == "west")
RotateImage(180);
img.className = "south";
else if (img.className == "south")
RotateImage(270);
img.className = "east";
else if (img.className == "east")
RotateImage(0);
img.className = "north";
);
);
function RotateImage(degree)
if (document.getElementById('canvas'))
var context = canvas.getContext('2d');
var cw = img.width, ch = img.height, cx = 0, cy = 0;
switch (degree)
case 90:
cw = img.height;
ch = img.width;
cy = img.height * (-1);
break;
case 180:
cx = img.width * (-1);
cy = img.height * (-1);
break;
case 270:
cw = img.height;
ch = img.width;
cx = img.width * (-1);
break;
canvas.setAttribute('width', cw);
canvas.setAttribute('height', ch);
context.rotate(degree * Math.PI / 180);
context.drawImage(img, cx, cy);
document.getElementById('hfData').value = canvas.toDataURL();
else
switch (degree)
case 0:
image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=0)';
break;
case 90:
image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=1)';
break;
case 180:
image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=2)';
break;
case 270:
image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)';
break;
</script>
【讨论】:
嗨。您正在回复超过 7 年的帖子。如果您的帖子很好地回答了这个问题,并且您觉得比已经发布的其他答案更好,您能否附上一些文字来解释您的答案是什么以及为什么它是一个很好的答案? 这将有助于旋转图像并将图像保存在任何角度图像中。例如,我们将图像旋转 180 度。我们可以将该图像(180 度)保存到我们的文件夹中。这里我们使用了画布。它对 ASP.NET 开发人员有帮助 您能否编辑您的帖子以更新您的描述,而不是将其作为评论发布。【参考方案5】:您可以尝试我的解决方案来旋转图像
<?php
ob_start();
// Content type
header('Content-type: image/jpeg');
class RotateImage
private $_path;
private $_degrees;
public function __construct($path, $degrees)
$this->_path = $path;
$this->_degrees = $degrees;
public function rotate()
$image = new Imagick($this->_path);
$image->rotateimage('black', $this->_degrees);
echo $image->getImageBlob();
exit();
if($_SERVER['REQUEST_METHOD'] == 'GET')
$sourceImagePath = isset($_GET['image_path']) ? $_GET['image_path'] : null;
$degrees = isset($_GET['degrees']) ? $_GET['degrees'] : 90;
$obj = new RotateImage($sourceImagePath, $degrees);
return $obj->rotate();
?>
【讨论】:
【参考方案6】:基于 nagarjun daram 使用图像和画布的纯 JavaScript 解决方案。
适用于数据 URL,完整的工作示例: https://jsfiddle.net/f8d46umz/7/
请注意,跨源图像可能无法正常工作,至少在小提琴上是这样。
主旋转代码:
function rotateDegrees(degrees, imgSrc, callback)
var canvasElement = document.getElementById('canvas'); //or create
if (!canvasElement || !canvasElement.getContext)
return showUnsupported();
//We use an additional img to get the sizes
var img = document.getElementById('tmpImg'); //or create
img.onload = function()
var cw = img.width,
ch = img.height,
cx = 0,
cy = 0;
switch (degrees)
case 90:
cw = img.height;
ch = img.width;
cy = img.height * (-1);
break;
case 180:
cx = img.width * (-1);
cy = img.height * (-1);
break;
case 270:
cw = img.height;
ch = img.width;
cx = img.width * (-1);
break;
var context = canvas.getContext('2d');
canvas.setAttribute('width', cw);
canvas.setAttribute('height', ch);
context.rotate(degrees * Math.PI / 180);
context.drawImage(img, cx, cy);
var result = canvas.toDataURL();
callback && callback(result);
img.src = imgSrc;
注意回调等待图片加载到临时img中
【讨论】:
以上是关于如何旋转图像并保存图像的主要内容,如果未能解决你的问题,请参考以下文章
获取 EXIF 方向标签,旋转到正确的方向,处理图像并以正确的方向保存图像