Upload image to c# server from iPhone - c#

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

Related

Cannot read a Bitmap image that I just saved in Base64

I try to load a picture (PNG), save-it in Base64 in a text file and reload it, but I only see gliberish pictures (black and white, very ugly, far from original!) after I load the picture from the text file.
Where's my problem?
BTW all examples (load the picture from image file, save to base64, load from base64) are all taken from SO questions.
First it's how a load the pictures from the PNG file:
try
{
var openFileDialog = new OpenFileDialog
{
CheckFileExists = true,
Multiselect = false,
DefaultExt = "png",
InitialDirectory =
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)
};
if (openFileDialog.ShowDialog() == true)
{
Bitmap img;
using (var stream = File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
img = new Bitmap(stream);
}
Logo.Source = BitmapToImageSource(img);
}
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString(), "An error occured", MessageBoxButton.OK, MessageBoxImage.Warning);
}
Save it to base64:
try
{
Bitmap img = BitmapSourceToBitmap2((BitmapSource) Logo.Source);
string base64String;
using (var stream = new MemoryStream())
{
img.Save(stream, ImageFormat.Png);
byte[] imageBytes = stream.ToArray();
base64String = Convert.ToBase64String(imageBytes);
}
string fileName = string.Format(CultureInfo.InvariantCulture, "image{0:yyyyMMddHHmmss}.txt",
DateTime.Now);
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), fileName);
using (var stream = File.Open(path, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
using (var writer = new StreamWriter(stream, System.Text.Encoding.UTF8))
{
writer.Write(base64String);
writer.Flush();
}
}
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString(), "An error occured", MessageBoxButton.OK, MessageBoxImage.Warning);
}
BitmapSourceToBitmap2:
int width = srs.PixelWidth;
int height = srs.PixelHeight;
int stride = width*((srs.Format.BitsPerPixel + 7)/8);
IntPtr ptr = IntPtr.Zero;
try
{
ptr = Marshal.AllocHGlobal(height*stride);
srs.CopyPixels(new Int32Rect(0, 0, width, height), ptr, height*stride, stride);
using (var btm = new Bitmap(width, height, stride, PixelFormat.Format1bppIndexed, ptr))
{
// Clone the bitmap so that we can dispose it and
// release the unmanaged memory at ptr
return new Bitmap(btm);
}
}
finally
{
if (ptr != IntPtr.Zero)
Marshal.FreeHGlobal(ptr);
}
And load it back from the file:
try
{
var openFileDialog = new OpenFileDialog
{
CheckFileExists = true,
Multiselect = false,
DefaultExt = "txt",
InitialDirectory =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
};
if (openFileDialog.ShowDialog() == true)
{
string base64String;
using (FileStream stream = File.Open(openFileDialog.FileName, FileMode.Open))
{
using (var reader = new StreamReader(stream))
{
base64String = reader.ReadToEnd();
}
}
byte[] binaryData = Convert.FromBase64String(base64String);
var bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = new MemoryStream(binaryData);
bi.EndInit();
Logo.Source = bi;
}
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString(), "An error occured", MessageBoxButton.OK, MessageBoxImage.Warning);
}
Here is a short code sequence that reads a JPG file into a byte array, creates a BitmapSource from it, then encodes it into a base64 string and writes that to file.
In a second step, the base64 string is read back from the file, decoded and a second BitmapSource is created.
The sample assumes that there is some XAML with two Image elements named image1 and image2.
Step 1:
var imageFile = #"C:\Users\Clemens\Pictures\DSC06449.JPG";
var buffer = File.ReadAllBytes(imageFile);
using (var stream = new MemoryStream(buffer))
{
image1.Source = BitmapFrame.Create(
stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
var base64File = #"C:\Users\Clemens\Pictures\DSC06449.b64";
var base64String = System.Convert.ToBase64String(buffer);
File.WriteAllText(base64File, base64String);
Step 2:
base64String = File.ReadAllText(base64File);
buffer = System.Convert.FromBase64String(base64String);
using (var stream = new MemoryStream(buffer))
{
image2.Source = BitmapFrame.Create(
stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
In case you need to encode an already existing BitmapSource into a byte array, use code like this:
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
using (var stream = new MemoryStream())
{
encoder.Save(stream);
buffer = stream.ToArray();
}

A Generic error occurred in GDI+ from picture of Ipad Air

Hi I have this error when a try to upload a picture downloaded via email from an Ipad Air Camera(JPG)
A Generic error occurred in GDI+
Here is the code, anyone can helps me? All the pictures are saving good except from this Ipad Air.
var pic = System.Web.HttpContext.Current.Request.Files[0];// canvi per Vendor/fileuploadmaster
Bitmap bmp = new Bitmap(pic.InputStream);
DateTime dtaken;
PropertyItem propItem;
try {
propItem = bmp.GetPropertyItem(36867);
string sdate = System.Text.Encoding.UTF8.GetString(propItem.Value).Trim();
string secondhalf = sdate.Substring(sdate.IndexOf(" "), (sdate.Length - sdate.IndexOf(" ")));
string firsthalf = sdate.Substring(0, 10);
firsthalf = firsthalf.Replace(":", "-");
sdate = firsthalf + secondhalf;
dtaken = DateTime.Parse(sdate);
}
catch {
dtaken = DateTime.Now;
}
//Fecha de última modificacion
//PropertyItem propItem = bmp.GetPropertyItem(306);
var newFilePath = ConfigurationManager.AppSettings["PathTmpPhotos"].ToString();
var FechaString = dtaken.ToString("yyMMddHHmmss");
var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + visitBrandId.ToString("D10") + "_" + FechaString + "_" + pic.FileName;
var tmpFilePath = newFilePath + newFileName;
pic.SaveAs(tmpFilePath);
var img = FileUtilities.ResizePhoto(newFilePath, newFileName, 800, 600);
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
// Create an Encoder object based on the GUID
// for the Quality parameter category.
Encoder myEncoder = Encoder.Quality;
// Create an EncoderParameters object.
// An EncoderParameters object has an array of EncoderParameter
// objects. In this case, there is only one
// EncoderParameter object in the array.
EncoderParameters myEncoderParameters = new EncoderParameters(1);
// 0L = NO Quality // 100L = High Quality
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 100L);
myEncoderParameters.Param[0] = myEncoderParameter;
img.Save(Path.Combine(newFilePath, newFileName), jpgEncoder, myEncoderParameters);
//img.Save(Path.Combine(newFilePath, newFileName));
The solution was in the ResizePhoto.
When the picture was taken with the mobile, is under 800x600 size, so this function cant resize the picture to a bigger size.
So, the solution was this:
var img = FileUtilities.ResizePhoto(newFilePath, newFileName, 300, 200);
Because dont exist any picture taken with the mobile smaller than 300x200
Regards

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.

ASP.NET uploading a file to Amazon S3

I am in the process of uploading images to Amazon S3, however i keep getting the error "Please specify either a Filename, provide a FileStream or provide a ContentBody to PUT an object into S3."
Basically i am uploading an image from a fileupload control and then hitting the code below. It uploads locally fine, but not to Amazon. The Credentials are alright so it only errors when it comes to uplaoding.
Can anyone see why this is happening please?
protected void uploadImg(int prodId, int prodFormat)
{
if (imgPack.HasFile)
{
string fileExt = Path.GetExtension(imgPack.PostedFile.FileName);
string filename = "img" + prodId + ".jpg";
// Specify the upload directory
string directory = Server.MapPath(#"\images\packshots\");
if (fileExt == ".jpeg" || fileExt == ".jpg" || fileExt == ".png")
{
if (packUK.PostedFile.ContentLength < 716800)
{
// Create a bitmap of the content of the fileUpload control in memory
Bitmap originalBMP = new Bitmap(packUK.FileContent);
// Calculate the new image dimensions
decimal origWidth = originalBMP.Width;
decimal origHeight = originalBMP.Height;
decimal sngRatio = origHeight / origWidth;
int newHeight = 354; //hight in pixels
decimal newWidth_temp = newHeight / sngRatio;
int newWidth = Convert.ToInt16(newWidth_temp);
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);
// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw the new graphic based on the resized bitmap
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
// Save the new graphic file to the server
string accessKey = "KEY HERE";
string secretKey = "KEY HERE";
AmazonS3 client;
using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey))
{
PutObjectRequest request = new PutObjectRequest();
request.BucketName="MyBucket";
request.CannedACL = S3CannedACL.PublicRead;
request.Key = "images/" + filename;
S3Response response = client.PutObject(request);
}
//newBMP.Save(directory + filename);
// Once finished with the bitmap objects, we deallocate them.
originalBMP.Dispose();
newBMP.Dispose();
oGraphics.Dispose();
}
}
else
{
notifybar.Attributes.Add("style", "display:block;");
notifybar.Attributes.Add("class", "failed");
notifyText.Text = "Error Text Here";
}
}
else
{
notifybar.Attributes.Add("style", "display:block;");
notifybar.Attributes.Add("class", "failed");
notifyText.Text = "Error Text Here";
}
}
You need to assign File or InputStream property of PutObjectRequest object. The code fragment should look like this one:
using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey))
{
var stream = new System.IO.MemoryStream();
originalBMP.Save(stream, ImageFormat.Bmp);
stream.Position = 0;
PutObjectRequest request = new PutObjectRequest();
request.InputStream = stream;
request.BucketName="MyBucket";
request.CannedACL = S3CannedACL.PublicRead;
request.Key = "images/" + filename;
S3Response response = client.PutObject(request);
}

send image in pixels using .net webservice

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

Categories