使用croppic与asp.net

opt*_*mus 5 php c# vb.net asp.net jquery

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

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

    var cropperOptions = {
        uploadUrl:'path_to_your_image_proccessing_file.php'
    }
Run Code Online (Sandbox Code Playgroud)

和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);

?>
Run Code Online (Sandbox Code Playgroud)

我怎样才能在asp.net中获得相同的行为.

Jos*_*nks 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>
Run Code Online (Sandbox Code Playgroud)

这就是我在控制器中输入的内容:

    [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;

    }
Run Code Online (Sandbox Code Playgroud)


Kem*_*min 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>
Run Code Online (Sandbox Code Playgroud)

保存原始文件.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
Run Code Online (Sandbox Code Playgroud)

作物.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
Run Code Online (Sandbox Code Playgroud)