我想使用Html 5或jquery或asp.net将图像转换为草图。此外,我想添加图像保存功能。请分享一些代码。提前谢谢
答案 0 :(得分:0)
这是完整的源代码,它使用2d canvas api oh html5将图像转换为灰度。但一定要使用支持html5 canvas的浏览器。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
//Global variables
var picWidth = 400; // width of the canvas
var picHeight = 400; // height of the canvas
var picLength = picWidth * picHeight; // number of chunks
var myImage = new Image(); // Create a new blank image.
// Load the image and display it.
function displayImage() {
// Get the canvas element.
canvas = document.getElementById("myCanvas");
// Make sure you got it.
if (canvas.getContext) {
// Specify 2d canvas type.
ctx = canvas.getContext("2d");
// When the image is loaded, draw it.
myImage.onload = function () {
// Load the image into the context.
ctx.drawImage(myImage, 0, 0);
// Get and modify the image data.
getColorData();
// Put the modified image back on the canvas.
putColorData();
}
// Define the source of the image.
// This file must be on your machine in the same folder as this web page.
myImage.src = "kestral.png";
}
}
function getColorData() {
myImage = ctx.getImageData(0, 0, 400, 400);
// Loop through data.
for (var i = 0; i < picLength * 4; i += 4) {
// First bytes are red bytes.
// Get red value.
var myRed = myImage.data[i];
// Second bytes are green bytes.
// Get green value.
var myGreen = myImage.data[i + 1];
// Third bytes are blue bytes.
// Get blue value.
var myBlue = myImage.data[i + 2];
// Fourth bytes are alpha bytes
// We don't care about alpha here.
// Add the three values and divide by three.
// Make it an integer.
myGray = parseInt((myRed + myGreen + myBlue) / 3);
// Assign average to red, green, and blue.
myImage.data[i] = myGray;
myImage.data[i + 1] = myGray;
myImage.data[i + 2] = myGray;
}
}
function putColorData() {
ctx.putImageData(myImage, 0, 0);
}
function noPhoto() {
alert("Please put a .png file in this folder.");
}
</script>
</head>
<body onload="displayImage()">
<h1>
Codeheaven.org Example (Image to Grayscale uisng html5 canvas)
</h1>
<p>
The original image is on the left and the modified image is on the right.
</p>
<img id="myPhoto" src="kestral.PNG" onerror="noPhoto()">
<canvas id="myCanvas" width="400" height="400">
</canvas>
</body>
</html>
在img src属性中提供图像的路径。并根据图像尺寸设置合适的图像宽度和高度。