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.
Related
following is the code added:
The image object is in the library.imaging.
"using System.Drawing;"
"using System.Drawing.Imaging;"
{
byte[] b = Convert.FromBase64String("R0lGODlhAQABAIAAA");
Image image;
using (MemoryStream memstr = new MemoryStream(b))
{
image = Image.FromStream(memstr);
}
}
Here is the new code I'm working on:
{
string base64BinaryStr = " ";
byte[] PDFDecoded = Convert.FromBase64String(base64BinaryStr);
string FileName = (#"C:\Users\Downloads\PDF " + DateTime.Now.ToString("dd-MM-yyyy-hh-mm"));
BinaryWriter writer = new BinaryWriter(File.Create(FileName + ".pdf"));
writer.Write(PDFDecoded);
string s = Encoding.UTF8.GetString(PDFDecoded);
}
So this is your current code:
byte[] PDFDecoded = Convert.FromBase64String(base64BinaryStr);
string FileName = (#"C:\Users\Downloads\PDF " + DateTime.Now.ToString("dd-MM-yyyy-hh-mm"));
BinaryWriter writer = new BinaryWriter(File.Create(FileName + ".pdf"));
writer.Write(PDFDecoded);
You don't actually need BinaryWriter for this. File.Create already gives you a FileStream:
FileStream writer = File.Create(FileName + ".pdf");
writer.Write(PDFDecoded, 0, PDFDecoded.Length);
But this will still have the problem you're experiencing because you're not flushing the data to it. We also need to close the file. Thankfully, we can wrap it in using and it will do both for us:
using (FileStream writer = File.Create(FileName + ".pdf"))
{
writer.Write(PDFDecoded, 0, PDFDecoded.Length);
}
But a simpler way to do this is:
File.WriteAllBytes(FileName + ".pdf", PDFDecoded);
As for PDF -> Image, you'll probably have to see if there is a library available for this (search "PDF to Image NuGet") that can help you with this as I don't think there is anything built-in.
Just a thought, you don't need to create a physical PDF file, you can have it in memory and convert it to image from there.
Now the problem is that you cannot use Image from System.Drawing.Imaging for this, it doesn't support reading PDF file.
Instead you'll need to search for some library that can do that.
For example, try GemBox.Pdf, you can use it like this:
string base64String = "...";
byte[] pdfBytes = Convert.FromBase64String(base64String);
using (PdfDocument pdfDocument = PdfDocument.Load(new MemoryStream(pdfBytes)))
{
ImageSaveOptions imageOptions = new ImageSaveOptions(ImageSaveFormat.Png);
string imageName = DateTime.Now.ToString("dd-MM-yyyy-hh-mm") + ".png";
pdfDocument.Save(#"C:\Users\Downloads\" + imageName, imageOptions);
}
I've used the code provided on this Convert example.
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
}
}
}
A friend of my is trying to upload a image on a Windows Form App to a chevereto website, using chevereto API and trying to get the link back(response from website), but its not really working...
API: Chevereto API
UPDATE: Code Added
static class Upload
{
string apiKey = "DEFAULT_API_KEY";
public string UploadImage(Image image)
{
WebClient webClient = new WebClient();
webClient.Headers.Add("key", apiKey);
webClient.Headers.Add("format", "txt");
System.Collections.Specialized.NameValueCollection Keys =
new System.Collections.Specialized.NameValueCollection();
try
{
string ht = "http://";
Keys.Add("image", ImageToBase64(image, ImageFormat.Bmp));
byte[] responseArray = webClient.UploadValues(ht + "mysite.com/api/1/upload/", Keys);
string result = Encoding.ASCII.GetString(responseArray);
return result;
}
catch (Exception e)
{
InternalConsole.LogError("Cannot upload image, error on next line: ");
InternalConsole.Log(e.Message);
return "none";
}
}
public string ImageToBase64(Image image, System.Drawing.Imaging.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;
}
}
}
Can someone show me how its done?
Thanks in advance.
Nevermind guys, my friend already fixed the problem.
He used WebRequest to send and receive the data.
He also said, dont forget to escape the string of base64(+, =, /), or the api will not accept properly and will return invalid base64 string.
Thanks anyway.
i am sending an image in byte[] and 3 strings to a webservice usingksoap but its not working for me , i am not sure where i am wrong, in sending image from Android and at receiving end, i am putting the code here kindly check it
Here is how i am converting image to byte[] at client (Android) side
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
and here is the code where i am sending it to webservice via Ksoap
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("Name", name);
request.addProperty("Email", email);
request.addProperty("Picture", encoded );
request.addProperty("Date", date);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport. call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
String str = result.toString();
and here is the webMethod where i am receiving this soap envelop
[WebMethod]
public String PutFile(String Name, String Email, String Picture, String Date)
{
String PictureByteString = Picture;
Image imgFromString = SaveByteArrayAsImage(PictureByteString);
DateTime.Now.ToShortDateString() + ".jpg"));
string serverpath = Server.MapPath("~/" + Email + "-" + DateTime.Now.ToShortDateString());
imgFromString.Save(serverpath, System.Drawing.Imaging.ImageFormat.Jpeg);
String Path = serverpath + ".Jpeg";
return Name;
}
private Image SaveByteArrayAsImage(string base64String)
{
byte[] bytes = Convert.FromBase64String(base64String);
image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
}
when i send data to webservice android LogCat shows me
java.io.IOException: HTTP request failed, HTTP status: 500
i think so which means that the data i am sending to webservice is not of correct type, so i tried to make String Picture to byte[] Picture in webmethod but result was same. I am not being able to figure out where i am wrong ...
Update:
now sending image in a Base64 string and java exception is gone but the webmethod is still not converting that Base64 string into image...
This is how i did it.
parameter passed to function is Base64 string
public string SendImage(string data)
{
byte[] myarray = Convert.FromBase64String(data);
MemoryStream memStream = new MemoryStream(myarray);
Image myimage = Image.FromStream(memStream);
myimage.Save("G:\\image.png", ImageFormat.Png);
return "succeeded";
}
This is working perfectly for me, Hope it helps.
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