web api post image with custom data - asp.net

I am trying to post some custom data with image to web api. Please take a look at the method below.
public void Post(FlyerDetails FlyerDetails)
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var filePath = HttpContext.Current.Server.MapPath("~/Flyers/" + httpRequest.Files[file].FileName);
Bitmap bmp = new Bitmap(httpRequest.Files[file].InputStream);
Graphics g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString(FlyerDetails.Message, new Font(FlyerDetails.FontColor, FlyerDetails.FontSize), Brushes.DarkRed, new PointF(0, 0));
g.Flush();
bmp.Save(filePath);
}
}
}
Now the problem is when i keep this method with parameter and post the data from fiddler it shows me 415 Unsupported Media Type error . If i remove the parameter then it is working fine. But i really need to pass the data along with the posted image.
Can any one suggest a good way to accomplish this ?
Thanks

After searching a lot i figured out the way to upload the data along with the image. Here is the revised version of the code. Hope that it will helpful to someone.
public async Task<HttpResponseMessage> Post()
{
var streamProvider = new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/Flyers/"));
await Request.Content.ReadAsMultipartAsync(streamProvider);
var response = Request.CreateResponse(HttpStatusCode.Created);
var filePath = "";// file path
if (System.IO.File.Exists(filePath))
{
string extension = Path.GetExtension(filePath);
Bitmap bmp = new Bitmap(filePath);
Graphics g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
Color brushColor = System.Drawing.ColorTranslator.FromHtml(streamProvider.FormData["FontColorCode"]);
g.DrawString(streamProvider.FormData["FontFamily"], new Font(brushColor.Name, Convert.ToInt32(streamProvider.FormData["FontSize"])), new SolidBrush(brushColor), new PointF(0, 0));
g.Flush();
bmp.Save(HttpContext.Current.Server.MapPath("~/" + Guid.NewGuid() + extension));
response.Headers.Location = new Uri(new Uri(HttpContext.Current.Request.Url.AbsoluteUri).GetLeftPart(UriPartial.Authority) + "/Flyers/" + Guid.NewGuid() + extension);
}
return response;
}
NOTE : One should post the data as mutipart-formdata.

this line also gets a post parameter along with uploaded file:
string value = HttpContext.Current.Request.Params.Get("key");

Related

ASP.NET Core Image Resize

I'm trying to resize imagine with System.Drawing but im taking that file as IFormFile and when i use the System.Drawing its just keep warning me to about that : cannot implicitly convert type 'System.Drawing.Bitmap' to 'Microsoft.AspNetCore.Http.IFormFile' . I need to resize those photos and save them as IFormFile but i dont know how to do that.
public Task<IFormFile> ResizeImagine300x300(IFormFile file)
{
Image image = Image.FromStream(file.OpenReadStream(), true, true);
var newImage = new Bitmap(1024, 768);
using (var g = Graphics.FromImage(newImage))
{
g.DrawImage(image, 0, 0, 1024, 768);
};
return newImage;//the point where i get the error
}
Is it possible to do it in my way?
If its not possible, then which way i should follow?
Thanks for any suggestion
Edit: I wanna return as a IFormFile because i have a method which is uploading those files to my database. here is my method :
public async Task<FileRepo> FileUploadToDatabase(List<IFormFile> files)
{
foreach (var file in files)
{
var fileName = Path.GetFileNameWithoutExtension(file.FileName);
var fileExtension = Path.GetExtension(file.FileName);
_fileRepo = new FileRepo
{
FileName = fileName,
FileExtension = fileExtension,
FileType = file.ContentType,
CreatedDate= DateTime.Now
};
using (var dataStream = new MemoryStream())
{
await file.CopyToAsync(dataStream);
_fileRepo.FileData = dataStream.ToArray();
}
}
return _fileRepo;
}
After that I'm uploading that _fileRepo variable to my database like that :
var File = _fileUploader.FileUploadToDatabase(files);
var FileResult = File.Result;
FileResult.ProductID = ProductID;
_unitOfWorkFR.RepositoryFileRepo.Create(FileResult);

How to save the picture take by xamarin media plugin to the localhost xampp?

I have connect my phone to my localhost(xampp) but i fail to save the picture take by xamarin plugin to my pc directory. Below is my code:
public MainPage()
{
InitializeComponent();
//CameraButton.Clicked += CameraButton_Clicked;
var request = new HttpRequestMessage();
request.RequestUri = new Uri("http://192.168.137.1/pic/");
request.Method = HttpMethod.Post;
request.Headers.Add("Accept", "application/json");
//var client = new HttpClient();
//HttpResponseMessage response = client.SendAsync(request);
}
Below is save photo code:
var file = CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
DefaultCamera = Plugin.Media.Abstractions.CameraDevice.Rear,
CompressionQuality = 92,
SaveToAlbum = false,
Directory= "http://192.168.137.1/pic/",
Name = DateTime.Now + "_test.jpg"
});
Can anyone share me idea how to make it done? Please help and thanks.

Getting "a generic error occurred in gdi+" only on live server, every thing is working on localhost

I am using the following code to resize and save an image. Please get me out of this error. I'm geting this error only on my live server, while it's working on localhost.
public void ResizeImage(Int32 height, Int32 width, Stream fromStream, String filename)
{
var image = System.Drawing.Image.FromStream(fromStream);
var newWidth = width;
var newHeight = height;
var thumbnailBitmap = new Bitmap(newWidth, newHeight);
var thumbnailGraph = Graphics.FromImage(thumbnailBitmap);
thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
thumbnailGraph.DrawImage(image, imageRectangle);
//thumbnailBitmap.Save(toStream, image.RawFormat);
String path = Server.MapPath("~/signatures/" + filename);
thumbnailBitmap.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
thumbnailGraph.Dispose();
thumbnailBitmap.Dispose();
image.Dispose();
}
Did you try Google? Seems like it could be caused by a few things. Since it only crashes on the server, my first guess would be that ASP.NET doesn't have write permission in the folder you're saving to. See here:
http://weblogs.asp.net/anasghanem/archive/2009/02/28/solving-quot-a-generic-error-occurred-in-gdi-quot-exception.aspx

How to add a 'System.Drawing.Image' to a 'System.Web.UI.WebControls.Image'

I have two functions:
Function 1: ImageToByteArray: Is used to Convert an Image into a Byte Array and then Store in an Oracle Database, in a BLOB Field.
public byte[] ImageToByteArray(string sPath)
{
byte[] data = null;
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
data = br.ReadBytes((int)numBytes);
return data;
}
Function 2: ByteArrayToImage: Is used to Convert a Byte Array from the Database into an Image:
public System.Drawing.Image ByteArrayToImage(byte[] byteArray)
{
MemoryStream img = new MemoryStream(byteArray);
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(img);
return returnImage;
}
In my Markup I have an Imgage Control:
<asp:Image ID="Image1" runat="server" />
In the Code Behind I want to Assign the Returned Value from Function 2 to (which is of type System.Drawing.Image) to the "image1" control which is of type (System.Web.UI.WebControls.Image).
Obviously I can't just assign:
image1 = ByteArrayToImage(byteArray);
because I'd get the following error: Cannot implicitly convert type 'System.Drawing.Image' to 'System.Web.UI.WebControls.Image'
Is there anyway to do this?
It looks like you just want a simple method to convert an image byte array into a picture. No problem. I found an article that helped me a lot.
System.Web.UI.WebControls.Image image = (System.Web.UI.WebControls.Image)e.Item.FindControl("image");
if (!String.IsNullOrEmpty(currentAd.PictureFileName))
{
image.ImageUrl = GetImage(currentAd.PictureFileContents);
}
else
{
image.Visible = false;
}
//The actual converting function
public string GetImage(object img)
{
return "data:image/jpg;base64," + Convert.ToBase64String((byte[])img);
}
PictureFileContents is a Byte[] and that's what the function GetImage is taking as an object.
You can't. WebControls.Image is just a HTML container for an image url - you can't store the image data directly in it, you just store the reference (url) to an image file.
If you need to retrieve image data dynamically, the usual approach is to create an image handler that will handle the request and return the image as a stream that the browser can display.
See this question
I think it is possible and I hope it be helpful. My solution for this is here:
public System.Web.UI.WebControls.Image HexStringToWebControlImage(string hexString)
{
var imageAsString = HexString2Bytes(hexString);
MemoryStream ms = new MemoryStream();
ms.Write(imageAsString, 0, imageAsString.Length);
if (imageAsString.Length > 0)
{
var base64Data = Convert.ToBase64String(ms.ToArray());
return new System.Web.UI.WebControls.Image
{
ImageUrl = "data:image/jpg;base64," + base64Data
};
}
else
{
return null;
}
}
public byte[] HexString2Bytes(string hexString)
{
int bytesCount = (hexString.Length) / 2;
byte[] bytes = new byte[bytesCount];
for (int x = 0; x < bytesCount; ++x)
{
bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);
}
return bytes;
}

Remote Image with basic authentication?

I would like to load a an image from an external domain and I have the below so far:
private function get_coverArt(coverArtID:String):void
{
var requestString:String = "/rest/getCoverArt.view?v=1.5.0&c=AirSub&id=" + coverArtID;
var requestURL:String = subServerURL + requestString;
myCoverArtLoader = new URLLoader();
var myRequest:URLRequest = new URLRequest();
var authHeader:URLRequestHeader = new URLRequestHeader();
authHeader.name = 'Authorization';
authHeader.value = 'Basic ' + credentials;
myRequest.requestHeaders.push(authHeader);
myRequest.url = requestURL;
myRequest.method = URLRequestMethod.GET;
myCoverArtLoader.dataFormat = URLLoaderDataFormat.BINARY;
myCoverArtLoader.addEventListener(Event.COMPLETE, set_coverArt);
myCoverArtLoader.load(myRequest);
}
private function set_coverArt(evt:Event) : void {
coverArtImg = new Image();
var loader:Loader = new Loader();
loader.loadBytes(myCoverArtLoader.data);
coverArtImg.source = loader;
}
This does not seem to work - any help?
Thanks!
Try setting the source directly like so:
private function set_coverArt(evt:Event) : void {
coverArtImg = new Image();
coverArtImg.source = myCoverArtLoader.data;
}
Also, check your authentication, here's a question I answered regarding the auth :
Actionscript 3: Reading an RSS feed that requires authentication

Resources