get result from public static string - c#

Is there a simple way to get the public static string result to the controller.
So im trying to make so when you upload you're image it gets resized.
i made a following code in my Toolbox
public static string ImageUpload(HttpPostedFileBase file, string SubFolder)
{
Guid gi = Guid.NewGuid();
string extension = Path.GetExtension(file.FileName);
using (var image = Image.FromStream(file.InputStream, true, true))
{
var thumbWidth = 700;
var thumbHeight = 700;
if (image.Width < image.Height)
{
//portrait image
thumbHeight = 640;
var imgRatio = (float)thumbHeight / (float)image.Height;
thumbWidth = Convert.ToInt32(image.Width * imgRatio);
}
else
if (image.Height < image.Width)
{
//landscape image
thumbWidth = 960;
var imgRatio = (float)thumbWidth / (float)image.Width;
thumbHeight = Convert.ToInt32(image.Height * imgRatio);
}
using (var thumb = image.GetThumbnailImage(
thumbWidth,
thumbHeight,
() => false,
IntPtr.Zero))
{
var jpgInfo = ImageCodecInfo.GetImageEncoders()
.Where(codecInfo => codecInfo.MimeType == "image/jpeg").First();
using (var encParams = new EncoderParameters(1))
{
string thumbPath = "~/Content/admin/images/" + SubFolder;
bool isExists = System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(thumbPath));
if (!isExists)
{
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(thumbPath));
}
var thumbPathFull = Path.Combine(HttpContext.Current.Server.MapPath(thumbPath), gi + extension);
string newfileurl = "/Content/admin/images/" + SubFolder + gi + extension;
long quality = 1500;
encParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
thumb.Save(thumbPathFull, jpgInfo, encParams);
return newfileurl;
}
}
}
so i want the value "return newfileurl;" to my controller so how do i call it. so i can save the the string to my db to get the image frontend
[HttpPost]
[ValidateInput(false)]
public ActionResult NewsCreate(NewsItem ni, HttpPostedFileBase file)
{
Guid gi = Guid.NewGuid();
if (file != null && file.ContentLength > 0)
{
CRUDHelper.ImageUpload(file, "newsimage");
ni.Image = **??????insert solution here??????**;
db.NewsItems.Add(ni);
db.SaveChanges();
}

CRUDHelper.ImageUpload(file, "newsimage"); already returns the result, you only have to assign it to something: ni.Image = CRUDHelper.ImageUpload(file, "newsimage");
– HimBromBeere

Related

how to apply filter on excel file in c# (asp.net mvc)

i need to filter an excel file that i fetch information from it
in my mvc web Application .
which package should i install , or which feature i should use? which command?
advance appreciated.
this is my code :
public ActionResult Upload(FormCollection formCollection)
{
var CourseList= new List<CourseTbl>();
if (Request != null)
{
HttpPostedFileBase file = Request.Files["UploadedFile"];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
string fileName = file.FileName;
string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
using (var package = new ExcelPackage(file.InputStream))
{
ExcelWorksheets currentSheet = package.Workbook.Worksheets;
ExcelWorksheet workSheet = currentSheet.First();
//i attempt below commands : (not worked)
//Microsoft.Office.Interop.Excel.AutoFilter
//workSheet.Cells.AutoFilter
var noOfCol = workSheet.Dimension.End.Column;
var noOfRow = workSheet.Dimension.End.Row;
for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
{
var Course = new CourseTbl();
Course.Course_id = Convert.ToInt32(workSheet.Cells[rowIterator, 1].Value);
Course.name = Convert.ToString(workSheet.Cells[rowIterator, 2].Value);
CourseList.Add(Course);
}
}
}
}
using (ExcelImportDBEntities excelImportDBEntities = new ExcelImportDBEntities())
{
foreach (var item in CourseList)
{
excelImportDBEntities.darsTbls.Add(item);
}
excelImportDBEntities.SaveChanges();
}
return View("Index");
}

How to fix "Value was either too large or too small for a UInt32" C#

I am trying to convert ActionScript3 code to C# that's like the main thing. However, with trying to convert one of the functions I got the error which is in the title when I was trying to convert a hexadecimal string to an int.
Basically, this code is supposed to take information for example user data and then do somethings and in the end return Base64 encoded text. The main error that I am aware of is at the part where "loc9 = Convert.ToInt32(loc8, 16);" is as that is where I am getting the error said in the title. I have tried researching similar issues others have had with something like this, but it just didn't seem the same and didn't really help me out.
(Btw I am sorry if this doesn't sound so clear, correct me or ask more questions if not understood)
Screenshot of error when called
My C# Code:
private static string hasher(string input)
{
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("x2"));
}
return sb.ToString();
}
public static string p(string param1)
{
var loc6 = "";
var loc7 = "";
var loc8 = "";
var loc9 = 0;
var loc2 = hasher(param1);
var loc4 = 0;
MemoryStream loc0 = new MemoryStream();
var loc3 = new byte[] { };
while(loc4 < loc2.Length * 2)
{
loc6 = loc2.Substring(loc4, loc4 + 1);
loc7 = loc2.Substring(loc4 + 1, loc4 + 2);
loc8 = "0x" + loc6 + loc7;
loc9 = Convert.ToInt32(loc8, 16);
new BinaryWriter(loc0).Write(loc9);
loc4 = loc4 + 2;
}
loc0.Position = 0;
loc3 = loc0.ToArray();
return Convert.ToBase64String(loc3, 0, 16);
}
public string calculateFromNewActorCreationData(string username, string password, byte[] small, byte[] full)
{
return calculateFromStrings(username, password, small, full);
}
public string calculateFromStrings(string param1, string param2, object param3, object param4)
{
var loc5 = param1 + param2 + fromByteArray(param3 as byte[]) + fromByteArray(param4 as byte[]) + p();
return p(loc5);
}
private string fromByteArray(byte[] param1)
{
var ms = new MemoryStream(param1);
List<byte> list2 = new List<byte>();
if (param1.Length <= 20)
return HexStringFromBytes(param1);
var loc3 = new byte[] { };
var loc4 = param1.Length / 20;
var loc5 = 0;
while (loc5 < 20)
{
ms.Position = loc4 * loc5;
list2.Add(new BinaryReader(ms).ReadByte());
loc5++;
}
loc3 = list2.ToArray();
return HexStringFromBytes(loc3);
}
private static string HexStringFromBytes(byte[] bytes)
{
var sb = new StringBuilder();
foreach (byte b in bytes)
{
var hex = b.ToString("x2");
sb.Append(hex);
}
return sb.ToString();
}
private string p()
{
MemoryStream stream = new MemoryStream();
new BinaryWriter(stream).Write(120);
new BinaryWriter(stream).Write(-38);
new BinaryWriter(stream).Write(99);
new BinaryWriter(stream).Write(16);
new BinaryWriter(stream).Write(32);
new BinaryWriter(stream).Write(51);
new BinaryWriter(stream).Write(41);
new BinaryWriter(stream).Write(-110);
new BinaryWriter(stream).Write(12);
new BinaryWriter(stream).Write(50);
new BinaryWriter(stream).Write(81);
new BinaryWriter(stream).Write(73);
new BinaryWriter(stream).Write(49);
new BinaryWriter(stream).Write(-56);
new BinaryWriter(stream).Write(13);
new BinaryWriter(stream).Write(48);
new BinaryWriter(stream).Write(54);
new BinaryWriter(stream).Write(54);
new BinaryWriter(stream).Write(14);
new BinaryWriter(stream).Write(48);
new BinaryWriter(stream).Write(46);
new BinaryWriter(stream).Write(2);
new BinaryWriter(stream).Write(0);
new BinaryWriter(stream).Write(45);
new BinaryWriter(stream).Write(-30);
new BinaryWriter(stream).Write(4);
new BinaryWriter(stream).Write(-16);
stream.Position = 0;
return Encoding.UTF8.GetString(stream.ToArray());
}
ActionScript3 Code:
private static function p(param1:String) : String
{
var _loc6_:String = null;
var _loc7_:String = null;
var _loc8_:String = null;
var _loc9_:int = 0;
var _loc2_:String = MD5.hash(param1);
var _loc3_:ByteArray = new ByteArray();
var _loc4_:int = 0;
while(_loc4_ < _loc2_.length * 2)
{
_loc6_ = _loc2_.slice(_loc4_,_loc4_ + 1);
_loc7_ = _loc2_.slice(_loc4_ + 1,_loc4_ + 2);
_loc8_ = "0x" + _loc6_ + _loc7_;
_loc9_ = int(_loc8_);
_loc3_.writeByte(_loc9_);
_loc4_ = _loc4_ + 2;
}
_loc3_.position = 0;
var _loc5_:Base64Encoder = new Base64Encoder();
_loc5_.encodeBytes(_loc3_,0,16);
return _loc5_.toString();
}
public function calculateFromNewActorCreationData(param1:NewActorCreationData, param2:ByteArray, param3:ByteArray) : String
{
return this.calculateFromStrings(param1.ChosenActorName,param1.ChosenPassword,param2,param3);
}
public function calculateFromStrings(param1:String, param2:String, param3:Object, param4:Object) : String
{
var _loc5_:String = param1 + param2 + this.fromByteArray(param3) + this.fromByteArray(param4) + this.p();
return p(_loc5_);
}
private function fromByteArray(param1:Object) : String
{
if(param1 == null)
{
return "";
}
var _loc2_:int = 20;
if(param1.length <= _loc2_)
{
return Hex.fromArray(param1 as ByteArray);
}
var _loc3_:ByteArray = new ByteArray();
var _loc4_:int = param1.length / _loc2_;
var _loc5_:int = 0;
while(_loc5_ < _loc2_)
{
param1.position = _loc4_ * _loc5_;
_loc3_.writeByte(param1.readByte());
_loc5_++;
}
return Hex.fromArray(_loc3_);
}
private function p() : String
{
var _loc1_:ByteArray = new ByteArray();
_loc1_.writeByte(120);
_loc1_.writeByte(-38);
_loc1_.writeByte(99);
_loc1_.writeByte(16);
_loc1_.writeByte(12);
_loc1_.writeByte(51);
_loc1_.writeByte(41);
_loc1_.writeByte(-118);
_loc1_.writeByte(12);
_loc1_.writeByte(50);
_loc1_.writeByte(81);
_loc1_.writeByte(73);
_loc1_.writeByte(49);
_loc1_.writeByte(-56);
_loc1_.writeByte(13);
_loc1_.writeByte(48);
_loc1_.writeByte(54);
_loc1_.writeByte(54);
_loc1_.writeByte(14);
_loc1_.writeByte(48);
_loc1_.writeByte(46);
_loc1_.writeByte(2);
_loc1_.writeByte(0);
_loc1_.writeByte(45);
_loc1_.writeByte(-30);
_loc1_.writeByte(4);
_loc1_.writeByte(-16);
_loc1_.uncompress();
_loc1_.position = 0;
return _loc1_.readUTF();
}
What I am expecting in the end is to be able to call the function having the returned Base64 encoded data show in a MessageBox (using messagebox as a test) instead of any errors popping up.
P.S - Besides the main problem I am having with this code, I also feel like the other functions I had converted aren't perfect or just might not be the same. So, if my main problem can be solved, if someone can also double check the other functions of my code make sure they are accurate that would be amazing and thanks in advance.
Looking at this overall, it appears the AS3 code is attempting to convert the MD5.hash result into a Base64 encoded string in the worst way possible (I believe it can be done in one line.)
So, instead of copying all the code to translate the hash to a hex string only to poorly translate it back to a binary array, just use the C# result which is already a binary array directly:
public static string p(string param1) {
byte[] loc3 = System.Security.Cryptography.MD5.Create().ComputeHash(System.Text.Encoding.ASCII.GetBytes(param1));
return Convert.ToBase64String(loc3, 0, 16);
}

app crashes before the request is sent to the server

I'm building an android app with Xamarin which communicates with an ASP.net server's API. I'm trying to upload a file to the server using the following lines of code:
public async Task<HttpResponseMessage> UploadFile(byte[] file)
{
var progress = new System.Net.Http.Handlers.ProgressMessageHandler();
//progress.HttpSendProgress += progress_HttpSendProgress;
using (var client = HttpClientFactory.Create(progress))
{
client.BaseAddress = new Uri(GlobalVariables.host);
// Set the Accept header for BSON.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/bson"));
var request = new uploadFileModel { data = file, dateCreated = DateTime.Now, fileName = "myvideooo.mp4", username = "psyoptica" };
// POST using the BSON formatter.
MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
var m = client.MaxResponseContentBufferSize;
var result = await client.PostAsync("api/media/upload", request, bsonFormatter);
return result.EnsureSuccessStatusCode();
}
}
The app crashes before the server receives the request. The file I'm trying to upload could be a video or an audio file. The server receives the request after the app has crashed. This works fine on the local server but the crash happens with the live server. My server side code looks like this:
[HttpPost]
[Route("upload")]
public async Task<HttpResponseMessage> Upload(uploadFileModel model)
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (ModelState.IsValid)
{
string thumbname = "";
string resizedthumbname = Guid.NewGuid() + "_yt.jpg";
string FfmpegPath = Encoding_Settings.FFMPEGPATH;
string tempFilePath = Path.Combine(HttpContext.Current.Server.MapPath("~/tempuploads"), model.fileName);
string pathToFiles = HttpContext.Current.Server.MapPath("~/tempuploads");
string pathToThumbs = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/thumbs");
string finalPath = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/flv");
string resizedthumb = Path.Combine(pathToThumbs, resizedthumbname);
var outputPathVid = new MediaFile { Filename = Path.Combine(finalPath, model.fileName) };
var inputPathVid = new MediaFile { Filename = Path.Combine(pathToFiles, model.fileName) };
int maxWidth = 380;
int maxHeight = 360;
var namewithoutext = Path.GetFileNameWithoutExtension(Path.Combine(pathToFiles, model.fileName));
thumbname = model.VideoThumbName;
string oldthumbpath = Path.Combine(pathToThumbs, thumbname);
var fileName = model.fileName;
File.WriteAllBytes(tempFilePath, model.data);
if (model.fileName.Contains("audio"))
{
File.WriteAllBytes(Path.Combine(finalPath, model.fileName), model.data);
string audio_thumb = "mic_thumb.jpg";
string destination = Path.Combine(pathToThumbs, audio_thumb);
string source = Path.Combine(pathToFiles, audio_thumb);
if (!System.IO.File.Exists(destination))
{
System.IO.File.Copy(source, destination, true);
}
Video_Struct vd = new Video_Struct();
vd.CategoryID = 0; // store categoryname or term instead of category id
vd.Categories = "";
vd.UserName = model.username;
vd.Title = "";
vd.Description = "";
vd.Tags = "";
vd.OriginalVideoFileName = model.fileName;
vd.VideoFileName = model.fileName;
vd.ThumbFileName = "mic_thumb.jpg";
vd.isPrivate = 0;
vd.AuthKey = "";
vd.isEnabled = 1;
vd.Response_VideoID = 0; // video responses
vd.isResponse = 0;
vd.isPublished = 1;
vd.isReviewed = 1;
vd.Thumb_Url = "none";
//vd.FLV_Url = flv_url;
vd.Embed_Script = "";
vd.isExternal = 0; // website own video, 1: embed video
vd.Type = 0;
vd.YoutubeID = "";
vd.isTagsreViewed = 1;
vd.Mode = 0; // filter videos based on website sections
long videoid = VideoBLL.Process_Info(vd, false);
}
else
{
using (var engine = new Engine())
{
engine.GetMetadata(inputPathVid);
// Saves the frame located on the 15th second of the video.
var outputPathThumb = new MediaFile { Filename = Path.Combine(pathToThumbs, thumbname+".jpg") };
var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(0), CustomHeight = 360, CustomWidth = 380 };
engine.GetThumbnail(inputPathVid, outputPathThumb, options);
}
Image image = Image.FromFile(Path.Combine(pathToThumbs, thumbname+".jpg"));
//var ratioX = (double)maxWidth / image.Width;
//var ratioY = (double)maxHeight / image.Height;
//var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(maxWidth);
var newHeight = (int)(maxHeight);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
Bitmap bmp = new Bitmap(newImage);
bmp.Save(Path.Combine(pathToThumbs, thumbname+"_resized.jpg"));
//File.Delete(Path.Combine(pathToThumbs, thumbname));
using (var engine = new Engine())
{
var conversionOptions = new ConversionOptions
{
VideoSize = VideoSize.Hd720,
AudioSampleRate = AudioSampleRate.Hz44100,
VideoAspectRatio = VideoAspectRatio.Default
};
engine.GetMetadata(inputPathVid);
engine.Convert(inputPathVid, outputPathVid, conversionOptions);
}
File.Delete(tempFilePath);
Video_Struct vd = new Video_Struct();
vd.CategoryID = 0; // store categoryname or term instead of category id
vd.Categories = "";
vd.UserName = model.username;
vd.Title = "";
vd.Description = "";
vd.Tags = "";
vd.Duration = inputPathVid.Metadata.Duration.ToString();
vd.Duration_Sec = Convert.ToInt32(inputPathVid.Metadata.Duration.Seconds.ToString());
vd.OriginalVideoFileName = model.fileName;
vd.VideoFileName = model.fileName;
vd.ThumbFileName = thumbname+"_resized.jpg";
vd.isPrivate = 0;
vd.AuthKey = "";
vd.isEnabled = 1;
vd.Response_VideoID = 0; // video responses
vd.isResponse = 0;
vd.isPublished = 1;
vd.isReviewed = 1;
vd.Thumb_Url = "none";
//vd.FLV_Url = flv_url;
vd.Embed_Script = "";
vd.isExternal = 0; // website own video, 1: embed video
vd.Type = 0;
vd.YoutubeID = "";
vd.isTagsreViewed = 1;
vd.Mode = 0; // filter videos based on website sections
//vd.ContentLength = f_contentlength;
vd.GalleryID = 0;
long videoid = VideoBLL.Process_Info(vd, false);
}
return result;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}`
What am I doing wrong here that's making the app crash. Is there a better way to do this?
Any help is appreciated.

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.
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;
}
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
Your code is working fine after change the single line of code.
Mismatch Parameter code:
var fileName = CropImage(originalFilePath, imgInitW, imgInitH, (int)imgW, (int)imgH, imgY1, imgX1, cropH, cropW);
Correct Code:
var fileName = CropImage(originalFilePath, imgInitW, imgInitH, (int)imgW, (int)imgH, imgY1, imgX1, cropW, cropH);
to this script i added something code and it has worked fine. It includes the rotation.
[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;
}
If you need to send byte[] data to the front.
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;
}
After searching for years! Here is the one i've compiled for ASP.net.
<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);
Full demo:
http://extreme.gen.tr/files/croppic_asp.net.zip
Guys, this post is the exact answer to this case. Needs some plus vote to let everyone know.

using RotateFlip to rotate bitmaps

I am having trouble rotating a scanned document that already has a qrcode on it.
I am checking for the qr code but when the code is upside down - i am having trouble flipping the page and trying to read for a qr code again. and i get this error message:
exception of type 'com.google.zxing.readerexception' was thrown
using (var fullImg = new Bitmap(workGif))
{
var halfW = fullImg.Width/2;
var halfH = fullImg.Height / 2;
var bandImg = fullImg.Clone(new System.Drawing.Rectangle(0, 0, halfW, halfH), fullImg.PixelFormat);
if (Process(bandImg) == null)
{
page.Rotate = (page.Rotate + 180) % 360;
}
string QRinfo = Process(bandImg);
MessageBox.Show(QRinfo);
string[] qcode = QRinfo.Split('/');
string gid = qcode[qcode.Count() - 1];
Guid pgGuid = new Guid(gid);
MessageBox.Show(QRinfo);
var ar = dc.Assessments.FirstOrDefault(c => c.ID == pgGuid);
if (ar != null)
{
var p = inputDocument.Pages[pg];
string opdName = FILESTORELOCATION + pgGuid.ToString() + ".pdf";
PdfDocument opd = new PdfDocument(opdName);
opd.Pages.Add(p);
opd.Close();
ar.StoragePath = opdName;
ar.LastUploadedDT = DateTime.UtcNow;
ar.UploadedByUserID = uploadingUser;
dc.SubmitChanges();
}
}
this is my process for decoding qr:
public string Process(Bitmap bitmap)
{
var reader = new com.google.zxing.qrcode.QRCodeReader();
try
{
LuminanceSource source = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height);
var binarizer = new HybridBinarizer(source);
var binBitmap = new BinaryBitmap(binarizer);
return reader.decode(binBitmap).Text;
}
catch (Exception e)
{
return e.Message;
}
}

Categories