使用croppic与asp.net

时间:2014-07-25 19:15:20

标签: c# php jquery asp.net vb.net

我正在使用croppic来调整图片大小,然后使用裁剪后的图片上传到数据库。但是他们的默认文档提供了PHP中的示例。

var cropperHeader = new Crop('yourId', cropperOptions);

    var cropperOptions = {
        uploadUrl:'path_to_your_image_proccessing_file.php'
    }

和php文件是这样的:

<?php

$imagePath = "temp/";

$allowedExts = array("gif", "jpeg", "jpg", "png", "GIF", "JPEG", "JPG", "PNG");
$temp = explode(".", $_FILES["img"]["name"]);
$extension = end($temp);

if ( in_array($extension, $allowedExts))
  {
  if ($_FILES["img"]["error"] > 0)
    {
         $response = array(
            "status" => 'error',
            "message" => 'ERROR Return Code: '. $_FILES["img"]["error"],
        );
        echo "Return Code: " . $_FILES["img"]["error"] . "<br>";
    }
  else
    {

      $filename = $_FILES["img"]["tmp_name"];
      list($width, $height) = getimagesize( $filename );

      move_uploaded_file($filename,  $imagePath . $_FILES["img"]["name"]);

      $response = array(
        "status" => 'success',
        "url" => $imagePath.$_FILES["img"]["name"],
        "width" => $width,
        "height" => $height
      );

    }
  }
else
  {
   $response = array(
        "status" => 'error',
        "message" => 'something went wrong',
    );
  }

  print json_encode($response);

?>

如何在asp.net中获得相同的行为。

5 个答案:

答案 0 :(得分:7)

这是ASP.NET MVC中的解决方案。关于存储图像的文件夹已做出一些假设。

.cshtml页面如下所示:

<div id="croppic"></div>
<script type="text/javascript">

        var cropperOptions = {
            uploadUrl: "UploadOriginalImage",
            cropUrl: "CroppedImage",
            imgEyecandy:true,
            imgEyecandyOpacity:0.2
        }
        var cropper = new Croppic('croppic', cropperOptions);

</script>

这就是我放入控制器的内容:

    [HttpPost]
    public string UploadOriginalImage(HttpPostedFileBase img)
    {
        string folder = Server.MapPath("~/Temp");
        string extension = Path.GetExtension(img.FileName);
        string pic = System.IO.Path.GetFileName(Guid.NewGuid().ToString());
        var tempPath = Path.ChangeExtension(pic, extension);
        string tempFilePath = System.IO.Path.Combine(folder, tempPath);
        img.SaveAs(tempFilePath);
        var image = System.Drawing.Image.FromFile(tempFilePath);
        var result = new 
        {
            status = "success",
            width = image.Width,
            height = image.Height,
            url = "../Temp/" + tempPath
        };
        return JsonConvert.SerializeObject(result);
    }

    [HttpPost]
    public string CroppedImage(string imgUrl, int imgInitW, int imgInitH, double imgW, double imgH, int imgY1, int imgX1, int cropH, int cropW)
    {
        var originalFilePath = Server.MapPath(imgUrl);
        var fileName = CropImage(originalFilePath, imgInitW, imgInitH, (int)imgW, (int)imgH, imgY1, imgX1, cropH, cropW);
        var result = new
        {
            status="success",
            url="../Cropped/" + fileName
        };
        return JsonConvert.SerializeObject(result);
    }

    private string CropImage(string originalFilePath, int origW, int origH, int targetW, int targetH, int cropStartY, int cropStartX, int cropW, int cropH)
    {
        var originalImage = Image.FromFile(originalFilePath);

        var resizedOriginalImage = new Bitmap(originalImage, targetW, targetH);
        var targetImage = new Bitmap(cropW, cropH);

        using (var g = Graphics.FromImage(targetImage))
        {
            g.DrawImage(resizedOriginalImage, new Rectangle(0, 0, cropW, cropH), new Rectangle(cropStartX, cropStartY, cropW, cropH), GraphicsUnit.Pixel);
        }
        string fileName = Path.GetFileName(originalFilePath);
        var folder = Server.MapPath("~/Cropped");
        string croppedPath = Path.Combine(folder, fileName);
        targetImage.Save(croppedPath);

        return fileName;

    }

答案 1 :(得分:2)

这是我到目前为止所做的...... 请注意,

  • 我还没有做过任何验证或错误检查..所以,请根据您的需要更改代码......
  • 以下代码中有一些常量和变量特定于我的项目。例如。文件名和路径..所以不要让他们混淆你并使用你自己的价值观。

在aspx页面中;

<div id="croppic"></div>
<script>
    $(document).ready(function () {
        var croppicHeaderOptions = {
            uploadUrl: 'SaveOriginal.ashx',
            cropUrl: 'Crop.ashx',
            customUploadButtonId: 'cropContainerHeaderButton',
            modal: false,
            loaderHtml: '<div class="loader bubblingG"><span id="bubblingG_1"></span><span id="bubblingG_2"></span><span id="bubblingG_3"></span></div> '
        }
        var croppic = new Croppic('croppic', croppicHeaderOptions);
    });
</script>

SaveOriginal.ashx

Imports System
Imports System.Web
Imports Newtonsoft.Json

Public Class CropKGNews : Implements IHttpHandler

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim up As HttpPostedFile = context.Request.Files(0)
        Dim upimg As System.Drawing.Image = System.Drawing.Image.FromStream(up.InputStream)

        Dim newFilename As String = System.IO.Path.GetRandomFileName() & System.IO.Path.GetExtension(up.FileName)
        up.SaveAs(MySettings.Constants.Folders.AdminTempPics & newFilename)

        Dim s As New successmsg With {.status = "success", .url = "img/_temp/" & newFilename, .width = upimg.Width, .height = upimg.Height}

        context.Response.Write(JsonConvert.SerializeObject(s))
    End Sub

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class

Public Class successmsg
    Public status As String
    Public url As String
    Public width As Integer
    Public height As Integer
End Class

Crop.ashx

Imports System
Imports System.Web
Imports System.Drawing
Imports System.Drawing.Drawing2D

Public Class CropKGNewsCrop : Implements IHttpHandler

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim imgUrl As String = context.Server.MapPath("~/_fhadm/" & context.Request("imgUrl"))
        Dim imgInitW As Decimal = context.Request("imgInitW")
        Dim imgInitH As Decimal = context.Request("imgInitH")
        Dim imgW As Decimal = context.Request("imgW")
        Dim imgH As Decimal = context.Request("imgH")
        Dim imgY1 As Decimal = context.Request("imgY1")
        Dim imgX1 As Decimal = context.Request("imgX1")
        Dim cropW As Decimal = context.Request("cropW")
        Dim cropH As Decimal = context.Request("cropH")

        Using bmp = New Bitmap(imgUrl)
            Using newbmp As Bitmap = resizeImage(bmp, New Size With {.Height = imgH, .Width = imgW})
                Using bmpcrop As Bitmap = newbmp.Clone(New Drawing.Rectangle With {.Height = cropH, .Width = cropW, .X = imgX1, .Y = imgY1}, newbmp.PixelFormat)
                    Dim croppedFilename As String = "cropped_" & System.IO.Path.GetRandomFileName() & System.IO.Path.GetExtension(imgUrl)
                    Dim croppedUrl As String = AdminTempNewsPic & croppedFilename
                    bmpcrop.Save(croppedUrl)
                    context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(New successmsg With {.status = "success", .url = "img/_temp/" & croppedFilename}))
                End Using
            End Using
        End Using
    End Sub


    Private Shared Function resizeImage(imgToResize As Image, size As Size) As Image
        Dim sourceWidth As Integer = imgToResize.Width
        Dim sourceHeight As Integer = imgToResize.Height

        Dim nPercent As Single = 0
        Dim nPercentW As Single = 0
        Dim nPercentH As Single = 0

        nPercentW = (CSng(size.Width) / CSng(sourceWidth))
        nPercentH = (CSng(size.Height) / CSng(sourceHeight))

        If nPercentH < nPercentW Then
            nPercent = nPercentH
        Else
            nPercent = nPercentW
        End If

        Dim destWidth As Integer = CInt(sourceWidth * nPercent)
        Dim destHeight As Integer = CInt(sourceHeight * nPercent)

        Dim b As New Bitmap(destWidth, destHeight)
        Dim g As Graphics = Graphics.FromImage(DirectCast(b, Image))
        g.InterpolationMode = InterpolationMode.HighQualityBicubic

        g.DrawImage(imgToResize, 0, 0, destWidth, destHeight)
        g.Dispose()

        Return DirectCast(b, Image)
    End Function


    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class

Public Class successmsg
    Public status As String
    Public url As String
End Class

答案 2 :(得分:1)

到这个脚本我添加了一些代码,它运行良好。它包括轮换。

    [HttpPost]
    public string UploadOriginalImage(HttpPostedFileBase img)
    {
        string folder = Server.MapPath("~/Images/Temp");
        string extension = Path.GetExtension(img.FileName);
        string pic = Path.GetFileName(Guid.NewGuid().ToString());
        string tempPath = Path.ChangeExtension(pic, extension);
        string tempFilePath = Path.Combine(folder, tempPath);
        img.SaveAs(tempFilePath);
        var image = System.Drawing.Image.FromFile(tempFilePath);

        var result = new
        {
            status = "success",
            width = image.Width,
            height = image.Height,
            url = "../Images/Temp/" + tempPath
        };
        return JsonConvert.SerializeObject(result);
    }

   [HttpPost]
    public string CroppedImage(FormCollection form)
    {
        string imgUrl = form["imgUrl"];
        int imgInitW = Convert.ToInt32(form["imgInitW"]);
        int imgInitH = Convert.ToInt32(form["imgInitH"]);
        double imgW = Convert.ToDouble(form["imgW"]);
        double imgH = Convert.ToDouble(form["imgH"]);
        int imgY1 = Convert.ToInt32(form["imgY1"]);
        int imgX1 = Convert.ToInt32(form["imgX1"]);
        int cropH = Convert.ToInt32(form["cropH"]);
        int cropW = Convert.ToInt32(form["cropW"]);
        double angulo = Convert.ToDouble(form["rotation"]);

        var originalFilePath = Server.MapPath(imgUrl);

        var fileName = CropImage(originalFilePath, imgInitW, imgInitH,
                        (int)imgW, (int)imgH, imgY1, imgX1, cropH, cropW, angulo);
        var result = new
        {
            status = "success",
            url = "../Images/Cropped/" + fileName
        };
        return JsonConvert.SerializeObject(result);
    }

   private string CropImage(string originalFilePath, int origW, int origH,
       int targetW, int targetH, int cropStartY, int cropStartX,
       int cropH, int cropW, double angle)
    {
        var originalImage = Image.FromFile(originalFilePath);
        originalImage = RotateImage(originalImage, (float)angle);
        var resizedOriginalImage = new Bitmap(originalImage, targetW, targetH);
        var targetImage = new Bitmap(cropW, cropH);

        using (var g = Graphics.FromImage(targetImage))
        {
            g.DrawImage(resizedOriginalImage, new Rectangle(0, 0, cropW, cropH),
                        new Rectangle(cropStartX, cropStartY, cropW, cropH),
                        GraphicsUnit.Pixel);
        }
        string fileName = Path.GetFileName(originalFilePath);
        var folder = Server.MapPath("~/Images/Cropped");
        string croppedPath = Path.Combine(folder, fileName);
        targetImage.Save(croppedPath);
        return fileName;
    }

    public static Bitmap RotateImage(Image img, float rotationAngle)
    {
        Bitmap bmp = new Bitmap(img.Width, img.Height);
        Graphics gfx = Graphics.FromImage(bmp);
        gfx.TranslateTransform((float)bmp.Width / 2, (float)bmp.Height / 2);
        gfx.RotateTransform(rotationAngle);
        gfx.TranslateTransform(-(float)bmp.Width / 2, -(float)bmp.Height / 2);
        gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
        gfx.DrawImage(img, new Point(0, 0));
        gfx.Dispose();
        return bmp;
    }

答案 3 :(得分:0)

如果您需要将byte []数据发送到前面。

 public class Upload : IHttpHandler
{
    public static readonly JavaScriptSerializer jss = new JavaScriptSerializer();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plan";

            var file = context.Request.Files["img"];


            Image image = System.Drawing.Image.FromStream(file.InputStream);
            context.Response.Write(jss.Serialize(new { status = "success", url = "data:image/jpg;base64," + CroppicUtils.ImageToBase64(image, CroppicUtils.GetImageFormat(image)), width = image.Width, height = image.Height }));
        }
        catch (Exception ex)
        {
            throw;
        }

    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

CroppicUtils

   public static string ImageToBase64(Image image, ImageFormat format)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            // Convert Image to byte[]
            image.Save(ms, format);
            byte[] imageBytes = ms.ToArray();

            // Convert byte[] to Base64 String
            string base64String = Convert.ToBase64String(imageBytes);
            return base64String;
        }
    }

public static ImageFormat GetImageFormat(System.Drawing.Image img)
    {
        if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
            return System.Drawing.Imaging.ImageFormat.Jpeg;
        if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Bmp))
            return System.Drawing.Imaging.ImageFormat.Bmp;
        if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png))
            return System.Drawing.Imaging.ImageFormat.Png;
        if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Emf))
            return System.Drawing.Imaging.ImageFormat.Emf;
        if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Exif))
            return System.Drawing.Imaging.ImageFormat.Exif;
        if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif))
            return System.Drawing.Imaging.ImageFormat.Gif;
        if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Icon))
            return System.Drawing.Imaging.ImageFormat.Icon;
        if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.MemoryBmp))
            return System.Drawing.Imaging.ImageFormat.MemoryBmp;
        if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Tiff))
            return System.Drawing.Imaging.ImageFormat.Tiff;
        else
            return System.Drawing.Imaging.ImageFormat.Wmf;
    }

答案 4 :(得分:-1)

寻找多年后!这是我为ASP.net编译的那个。

&#13;
&#13;
	
	<div class="container">
		<div class="row mt ">
			<div class="col-lg-4 ">
                <div id="cropContainerMinimal"></div>
			</div>		
		</div>		
	</div>
	
	

	<script src=" https://code.jquery.com/jquery-2.1.3.min.js"></script>
   	<script src="scripts/croppic/croppic.min.js"></script>
    

    <script>
        var croppicContaineroutputMinimal = {
            uploadUrl: 'scripts/croppic/Uploader.ashx',
            cropUrl: 'scripts/croppic/Crop.ashx',
            modal: false,
            doubleZoomControls: false,
            rotateControls: false,
            loaderHtml: '<div class="loader bubblingG"><span id="bubblingG_1"></span><span id="bubblingG_2"></span><span id="bubblingG_3"></span></div> ',
            onBeforeImgUpload: function () { console.log('onBeforeImgUpload') },
            onAfterImgUpload: function () { console.log('onAfterImgUpload') },
            onImgDrag: function () { console.log('onImgDrag') },
            onImgZoom: function () { console.log('onImgZoom') },
            onBeforeImgCrop: function () { console.log('onBeforeImgCrop') },
            onAfterImgCrop: function () { console.log('onAfterImgCrop') },
            onReset: function () { console.log('onReset') },
            onError: function (errormessage) { console.log('onError:' + errormessage) }
        }
        var cropContaineroutput = new Croppic('cropContainerMinimal', croppicContaineroutputMinimal);

     
&#13;
&#13;
&#13;

完整演示: http://extreme.gen.tr/files/croppic_asp.net.zip

伙计们,这篇文章是这个案例的确切答案。需要一些加投票才能让每个人都知道。