Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use croppic with asp.net

I am using croppic to resize my image and then use the cropped image to upload to the database. But their default documentation provides examples in PHP.

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

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

and the php file is like this:

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

?>

How can I get the same behavior in asp.net.

like image 750
optimus Avatar asked Jul 25 '14 19:07

optimus


2 Answers

This is what I've done so far.. Please note,

  • I have not done any validation or error check yet.. So, please change the code according to your needs...
  • There are some constants and variables in the below code specific to my project. E.g. filenames and paths.. So don't let them confuse you and use your own values.

In the aspx page;

<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
like image 34
Subliminal Hash Avatar answered Sep 28 '22 19:09

Subliminal Hash


Here's a solution in ASP.NET MVC. Some assumptions have been made regarding folders to store the images in.

The .cshtml page looks like this:

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

And this is what I put in my controller:

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

    }
like image 171
Josh Hanks Avatar answered Sep 28 '22 19:09

Josh Hanks