send image in pixels using .net webservice - c#

i wrote a webservice for send image in pixels form. it is working fine but when we give large amount of data in parameter it do not take full data. it take limited data or small image.
is this parameter limit? or How i give large data in parameter?
Here is my code
[WebMethod]
public XmlDocument testuploadimage(string image)
{
XmlDocument login = new XmlDocument();
XmlDeclaration dec = login.CreateXmlDeclaration("1.0", null, null);
login.AppendChild(dec);
XmlElement root = login.CreateElement("CreateUser");
login.AppendChild(root);
try
{
string actFolder = Server.MapPath("~/Images/");
string s = image.Replace(" ", string.Empty);
string imgname = DateTime.UtcNow.ToString().Replace(" ", "").Replace("AM", "").Replace("PM", "").Replace("/", "").Replace("-", "").Replace(":", "") + ".png";
// string imgname = DateTime.UtcNow.ToString("yyyyMMddHHmm") + ".png";
byte[] imageBytes = Convert.FromBase64String(image.Replace(" ","+"));
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// MemoryStream ms = new MemoryStream(imageBytes);
// Convert byte[] to Image
// ms.Write(imageBytes, 0, imageBytes.Length);
Image image2 = Image.FromStream(ms);
image2.Save(actFolder + imgname);
XmlElement root1 = login.CreateElement("uploaded");
root1.InnerText = "true";
root.AppendChild(root1);
XmlElement root2 = login.CreateElement("path");
root2.InnerText = "http://Myserver/HeritageWebServices/Images/" + imgname;
root.AppendChild(root2);
return login;
}
catch (Exception ex)
{
ErrLogMgr.LogErrorMessage(string.Format("{0}{1}", "testuploadimage() for the image :",
image), "testUploadimage Inputs",
ERRORSOURCE.CSASERVICE);
XmlDocument cd = new XmlDocument();
cd.LoadXml("<Message>" + ex + "</Message>");
return cd;

Two things
Try to change the maxRequestLength on the web.config file.
i see that you are using base64 to send the image, you could try to compress the bytearray before convert it to base64, to reduce the image or try to convert to a more compressed image type (ej: bmp to png).
regards

Related

Convert jpg string to image

I have a jpg strign stored in "(string)HttpContext.Current.Session["image" + 0];" that I am trying to convert to a System.Drawing.Image.
I know the string is correct, because when I do this -
img.Src = "data:image/jpg;base64," + (string)HttpContext.Current.Session["image" + 0];
Everying works as intended.
But when I do this -
string inputString = (string)HttpContext.Current.Session["image" + 0];
byte[] imageBytes = Convert.FromBase64String(inputString);
using (MemoryStream ms = new MemoryStream(imageBytes))
{
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
}
I get and error telling me the format is incorrect when trying to create an image from the stream.
Please help
don't you need to convert webp to jpg/png first?
for example WebP-wrapper
using (WebP webp = new WebP())
{
var image = webp.Decode(imageBytes );
}

ASP.NET to convert binary data to string

I'm trying to develop API that returns a profile of employees including their pictures, the images are stored in SQL database as image data type
TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap bmp = (Bitmap)typeConverter.ConvertFrom(Emp.img);
//3
var Fs = new FileStream(HostingEnvironment.MapPath("~/Images") + #"\I" + id.ToString() + ".png", FileMode.Create);
bmp.Save(Fs, ImageFormat.Png);
bmp.Dispose();
//4
Image img = Image.FromStream(Fs);
Fs.Close();
Fs.Dispose();
//5
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Png);
//6
response.Content = new ByteArrayContent(ms.ToArray());
ms.Close();
ms.Dispose();
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
response.StatusCode = HttpStatusCode.OK;
return response;
}
I want to use this API in Android Studio where I have to convert the image data type to string or any other applicable data time with Volley.
I'll use a base64 representation of the image:
byte[] imageAsBytes = File.ReadAllBytes(#"your\path\to\image.png");
string imageAsString = Convert.ToBase64String(imageArray);
Then send it back to the Android Studio client and do the following:
byte[] imageAsStringInAndroidStudio = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Just check if you have to strip the "data:image/jpg;base64" from the data before parsing it into Android Studio.

Extract Equation type of image from MS Word in c#

While importing the table content of MSWord fetching the XML of particular cell content those also have the Maths equation for which wordml(Word-XML) gives us the image of type wmz and provide us the image string of the same.
So I used that image string to create the image and save through our application at some particular location using code as below.
if (imageType == "wmz")
{
GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Decompress);
MemoryStream outStream = new MemoryStream();
int readCount;
byte[] data = new byte[128];
do
{
readCount = gzipStream.Read(data, 0, data.Length);
outStream.Write(data, 0, readCount);
}
while (readCount == 128);
File.WriteAllBytes(path + #"\XMLPictureWmf.wmf", outStream.GetBuffer());
outStream.Close();
outStream.Dispose();
Metafile mf;
mf = new Metafile(path + #"\XMLPictureWmf.wmf");
mf.Save(path + #"\XMLPicturepng.png");
imageString = path + #"\XMLPicturepng.png";
}
Now if I am going for creating png/jpeg type of image I get the blank space for the same so in order to get image save i have to use wmf as image type.
So the problem arises when I save that image as wmf. Image use get bold and doesn't use to get the exact image as of word.
Kindly help me out to extract the wmz type of image from wordml(word-XML) with exact match and resolution as of word.
My code of fetching the word cell content in form of XML from Word doc is as follows:
public string GetImagefromWord(string filePath)
{
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
object miss = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(filePath, miss, miss, miss, miss);
foreach (Microsoft.Office.Interop.Word.Row aRow in docs.Tables[0].Rows)
{
foreach (Microsoft.Office.Interop.Word.Cell aCell in aRow.Cells)
{
string xml = aCell.Range.XML;
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(xml);
****//xpictNode-Node of word XML having Image****
string imageType = xpictNode.Attributes["w:name"].Value.Substring(xpictNode.Attributes["w:name"].Value.LastIndexOf('.') + 1);
string path = Path.GetDirectoryName(Application.ExecutablePath);
byte[] byteBuffer = Convert.FromBase64String(xdoc.xpictNode.InnerText);
MemoryStream memoryStream = new MemoryStream(byteBuffer);
string img = " <img src= data:image/bmp;base64," + Convert.ToBase64String(File.ReadAllBytes(GetImageString(memoryStream, path, imageType))) + " />";
//Function GetImageString() is shown above
}
}
}

Upload image to c# server from iPhone

I want to upload a image to my server form iPhone
To upload image my code is
UIImage *image = [UIImage imageNamed:#"bg_DName.png"];
NSMutableData *imageData = (NSData*)UIImagePNGRepresentation(image);
NSString *string = [NSString stringWithFormat:#"http://myServer/HeritageWebServices/Service.asmx/testuploadimage"];
[self setRequest1:[ASIFormDataRequest requestWithURL:[NSURL URLWithString:string]]];
[request1 setPostValue:#"test" forKey:#"value1"];
[request1 setPostValue:#"test" forKey:#"value2"];
[request1 setPostValue:#"test" forKey:#"value3"];
[request1 setTimeOutSeconds:20];
[request1 setDelegate:self];
[request1 setDidFailSelector:#selector(uploadFailed:)];
[request1 setDidFinishSelector:#selector(uploadFinished:)];
[request1 setPostBody:imageData];
// NSLog(#"image %#",imageData);
[request1 setData:imageData withFileName:#"photo.png" andContentType:#"image/png" forKey:#"photo"];
[request1 startAsynchronous];
With the above code i am not able upload image.
UIImage *image = [UIImage imageNamed:#"bg.png"];
NSData *imageData = UIImagePNGRepresentation(image);
//NSLog(#"imageData %#",imageData);
NSString *dt = [[imageData description] stringByTrimmingCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
dt = [dt stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *string = [NSString stringWithFormat:#"http://myServer/HeritageWebServices/Service.asmx/testuploadimage?image=%#",dt];
// NSLog(#"urlstring %#",string);
request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:string]];
//
[request startAsynchronous];
If i try like this i can upload small image but not large images.Here i am sending the image in the request parameter as string.
My c# code to receive image
[WebMethod]
public byte[] testuploadimage(string image)
{
byte[] imageBytes;
System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://myServer/HeritageWebServices/Service.asmx/testuploadimage");
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/octet-stream";
httpWebRequest.ContentLength = image.Length;
XmlDocument login = new XmlDocument();
XmlDeclaration dec = login.CreateXmlDeclaration("1.0", null, null);
login.AppendChild(dec);
XmlElement root = login.CreateElement("CreateUser");
login.AppendChild(root);
//try
//{
string actFolder = Server.MapPath("~/Images/");
string s = image.Replace(" ", string.Empty);
ErrLogMgr.LogErrorMessage(string.Format("{0}{1}", "testuploadimage() for the image :",
image), "testUploadimage Inputs",
ERRORSOURCE.CSASERVICE);
string imgname = DateTime.UtcNow.ToString().Replace(" ", "").Replace("AM", "").Replace("PM", "").Replace("/", "").Replace("-", "").Replace(":", "") + ".png";
// string imgname = DateTime.UtcNow.ToString("yyyyMMddHHmm") + ".png";
// byte[] imageBytes = Convert.FromBase64String(image.Replace(" ","+"));
imageBytes = HexStringToByteArray(s);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// MemoryStream ms = new MemoryStream(imageBytes);
// Convert byte[] to Image
// ms.Write(imageBytes, 0, imageBytes.Length);
ErrLogMgr.LogErrorMessage(string.Format("{0}{1}", "testuploadimage() for the image :",
image), "testUploadimage Inputs",
ERRORSOURCE.CSASERVICE);
Image image2 = Image.FromStream(ms);
ErrLogMgr.LogErrorMessage(string.Format("{0}{1}", "testuploadimage() for the image :",
image), "testUploadimage Inputs",
ERRORSOURCE.CSASERVICE);
// System.Drawing.Bitmap image2 = new System.Drawing.Bitmap(ms);
image2.Save(actFolder + imgname);
XmlElement root1 = login.CreateElement("uploaded");
root1.InnerText = "true";
root.AppendChild(root1);
XmlElement root2 = login.CreateElement("path");
root2.InnerText = "http://myServer/HeritageWebServices/Images/" + imgname;
root.AppendChild(root2);
// return login;
return imageBytes;
// }
//catch (Exception ex)
//{
// ErrLogMgr.LogErrorMessage(string.Format("{0}{1}", "testuploadimage() for the image :",
// image), "testUploadimage Inputs",
// ERRORSOURCE.CSASERVICE);
// XmlDocument cd = new XmlDocument();
// cd.LoadXml("<Message>" + ex + "</Message>");
// // return cd;
// return imageBytes;
//}
}
private byte[] HexStringToByteArray(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;
}
}
For the large image exception which i am getting on server is
System.Runtime.InteropServices.ExternalException (0x80004005): A generic error occurred in GDI+. at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) at System.Drawing.Image.Save(String filename, ImageFormat format) at System.Drawing.Image.Save(String filename) at Heritage.Service.testuploadimage(String image) –
Can anybody help me.. What am i doing wrong
Is the problem with my iPhone code of with my c# code.
Thanx!!!
0x80004005 translates to access denied. So, it looks like it's server side config.
Look at the permissions on the path you are trying to save the image as. Also ensure the appPool identity or the end user has write permissions (depends on your asp.net security configuration/delegation settings).

how to upload the image from iphone and using .NET webservices

I want to upload the image using the .NET webservices and that will be called from iphone image.
the format of text that iphone is sending to me is like this.
http://d8768157.u118.c6.ixwebhosting.com/iphoneimg/image.txt
In which datatype i must convert this data and then save that in image format.
If you have any other method then please tell me.
I have tried converting this data in the byte[] but it is giving me error. here is my code. For what i have tried. please help me out.
[WebMethod]
public XmlDocument testuploadimage(string image)
{
XmlDocument login = new XmlDocument();
XmlDeclaration dec = login.CreateXmlDeclaration("1.0", null, null);
login.AppendChild(dec);
XmlElement root = login.CreateElement("CreateUser");
login.AppendChild(root);
try
{
string actFolder = Server.MapPath("~/iphoneimg/");
string imgname = DateTime.UtcNow.ToString().Replace(" ", "").Replace("AM", "").Replace("PM", "").Replace("/", "").Replace("-", "").Replace(":", "") + ".png";
Bitmap map;
using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(image)))
using (FileStream fs = File.Create(actFolder + imgname))
{
map = (Bitmap)Image.FromStream(stream);
map.Save(fs, System.Drawing.Imaging.ImageFormat.Gif);
}
XmlElement root1 = login.CreateElement("uploaded");
root1.InnerText = "true";
root.AppendChild(root1);
XmlElement root2 = login.CreateElement("path");
root2.InnerText = "http://d8768157.u118.c6.ixwebhosting.com/iphoneimg/" + imgname;
root.AppendChild(root2);
return login;
}
catch (Exception ex)
{
throw ex;
}
}
this is the error i m getting
Invalid character in a Base-64 string.
Thanks
BHAVIK GOYAL
[WebMethod]
public XmlDocument testuploadimage(string image)
{
XmlDocument login = new XmlDocument();
XmlDeclaration dec = login.CreateXmlDeclaration("1.0", null, null);
login.AppendChild(dec);
XmlElement root = login.CreateElement("CreateUser");
login.AppendChild(root);
try
{
string actFolder = Server.MapPath("~/iphoneimg/");
string imgname = DateTime.UtcNow.ToString().Replace(" ", "").Replace("AM", "").Replace("PM", "").Replace("/", "").Replace("-", "").Replace(":", "") + ".Png";
byte[] imageBytes = Convert.FromBase64String(image.Replace(" ","+"));
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image image2 = System.Drawing.Image.FromStream(ms, true);
image2.Save(actFolder + imgname);
XmlElement root1 = login.CreateElement("uploaded");
root1.InnerText = "true";
root.AppendChild(root1);
XmlElement root2 = login.CreateElement("path");
root2.InnerText = "http://d8768157.u118.c6.ixwebhosting.com/iphoneimg/" + imgname;
root.AppendChild(root2);
return login;
}
catch (Exception ex)
{
throw ex;
}
}
I got the answers...
thanks to all....
The error you're getting is a fundamental problem with your situation.
You are passing a non-Base64 string to Convert.FromBase64String().
Looking at the link you sent, the iPhone looks like it's sending hex characters with spaces.
You options are to either have the iPhone send you Base64, or remove the spaces and convert what the iPhone is sending now.
Here is a link with code
converting Hex to byte[].
Here is a link on what Base64
encoding is.
Here is a link describing
hexadecimal, which is what the
iPhone is sending you.

Categories