GDI+ Error - loading image in Asp.net. Student [duplicate] - asp.net

I create an asp.net 4.0 web application which has a web service for uploading images. I am uploading images by sending the image in form of Base64 string from my mobile app to the web service.
Following is my code:
public string Authenticate(string username, string password, string fileID, string imageData)
{
Dictionary<string, string> responseDictionary = new Dictionary<string, string>();
bool isAuthenticated = true; // Set this value based on the authentication logic
try
{
if (isAuthenticated)
{
UploadImage(imageData);
string result = "success";
var message = "Login successful";
responseDictionary["status"] = result;
responseDictionary["message"] = message;
}
}
catch (Exception ex)
{
responseDictionary["status"] = ex.Message;
responseDictionary["message"] = ex.StackTrace;
}
return new JavaScriptSerializer().Serialize(responseDictionary);
}
private void UploadImage(string uploadedImage)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(uploadedImage);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)Image.FromStream(ms);
string uploadPath = Server.MapPath("..\\uploads\\") + DateTime.Now.Ticks.ToString() + ".jpeg";
ms.Close();
bitmap.Save(uploadPath, System.Drawing.Imaging.ImageFormat.Jpeg);
bitmap.Dispose();
}
This code was working fine on my local ASP.NET development server and I was able to see the uploaded image in my "uploads" directory. However, after transferring the code to the FTP directory, I am now getting the following error:
A generic error occurred in GDI+
I have checked that the upload directory has proper permission by creating a dummy .aspx page and creating a text file on page_load, and it works fine.
Even after doing google search, I was not able to solve this problem. Can anybody help me fixing this?
Thanks a lot in advance.

Instead of writing directly to files, save your bitmap to a MemoryStream and then save the contents of the stream to disk. This is an old, known issue and, frankly, I don't remember all the details why this is so.
MemoryStream mOutput = new MemoryStream();
bmp.Save( mOutput, ImageFormat.Png );
byte[] array = mOutput.ToArray();
// do whatever you want with the byte[]
In your case it could be either
private void UploadImage(string uploadedImage)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(uploadedImage);
string uploadPath = Server.MapPath("..\\uploads\\") + DateTime.Now.Ticks.ToString() + ".jpeg";
// store the byte[] directly, without converting to Bitmap first
using ( FileStream fs = File.Create( uploadPath ) )
using ( BinaryWriter bw = new BinaryWriter( fs ) )
bw.Write( imageBytes );
}
or
private void UploadImage(string uploadedImage)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(uploadedImage);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)Image.FromStream(ms);
string uploadPath = Server.MapPath("..\\uploads\\") + DateTime.Now.Ticks.ToString() + ".jpeg";
ms.Close();
// convert to image first and store it to disk
using ( MemoryStream mOutput = new MemoryStream() )
{
bitmap.Save( mOutput, System.Drawing.Imaging.ImageFormat.Jpeg);
using ( FileStream fs = File.Create( uploadPath ) )
using ( BinaryWriter bw = new BinaryWriter( fs ) )
bw.Write( mOutput.ToArray() );
}
}

Furthermore I think it's worth pointing out that when MemoryStream is used, stream must always be closed and save method MUST be called before the stream closure
byte[] byteBuffer = Convert.FromBase64String(Base64String);
MemoryStream memoryStream = new MemoryStream(byteBuffer);
memoryStream.Position = 0;
Bitmap bmpReturn = (Bitmap)Bitmap.FromStream(memoryStream);
bmpReturn.Save(PicPath, ImageFormat.Jpeg);
memoryStream.Close();

Related

Converting Byte[] to stream file asp.net

i need to converting Byte() to stream then flush
its in asp.net application
here is my code :
Dim fileBytes As Byte() = Nothing
....
apiProp.BodyRequest = New JavaScriptSerializer().Serialize(entFile)
apiProp.EndPoint = "example.com/DownloadFile"
apiProp = api.MessageInvoke(apiProp)
entResponse = JsonConvert.DeserializeObject(Of FileResponse)(apiProp.BodyResponse)
fileBytes = Convert.FromBase64String(entFile.fileContent)
i've tried :
Response.BinaryWrite(fileBytes)
Response.Flush()
and i've tried any filestream, memorystream etc. the file ask to download, but if i download the file, the file get corrupted
i need the file converted to stream because i have to add the watermark on the image file. im using groupdocs.watermark for adding the watermark.
using (Stream InputStream = fl.PostedFile.InputStream)
{
Object o = new object();
lock (o)
{
byte[] buffer = new byte[InputStream.Length];
InputStream.Read(buffer, 0, (int)InputStream.Length);
lock (o)
{
File.WriteAllBytes(rpath, buffer);
buffer = null;
}
InputStream.Close();
}
}

ASP .Net MVC: getting 352 error on uploading video to Facebook using Facebook SDK version 6.8

I am getting the following error when trying to upload video to Facebook from my web application:
"(OAuthException - #352) (#352) Sorry, the video file you selected is in a format that we don't support"
public void uploadVideoToFaceBook(string accessToken, string videoURL, string videoTitle)
{
byte[] stream = DownloadVideoAsByte(videoURL);
var mediaObject = new FacebookMediaObject
{
FileName = videoTitle,
ContentType = "video/mp4"
};
mediaObject.SetValue(stream);
try
{
var fb = new FacebookClient(accessToken);
dynamic result = fb.Post("me/videos",
new
{
message = "my first photo upload using Facebook SDK for .NET",
file = mediaObject
});
var videoId = (string)result["vid"];
}
catch (FacebookApiException ex)
{
throw;
}
}
Note: DownloadVideoAsByte() returns byte[] from azure blob. following is the code:
public byte[] DownloadVideoAsByte(string videoUrl)
{
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(videoUrl);
httpRequest.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
System.IO.Stream dataStream = httpResponse.GetResponseStream();
System.IO.StreamReader streamReader = new System.IO.StreamReader(dataStream);
String data = streamReader.ReadToEnd();
byte[] buffer = new byte[data.Length];
for (int i = 0; i < data.Length; i++)
buffer[i] = (byte)data[i];
dataStream.Close();
streamReader.Close();
return buffer;
}
Any help in this regard shall be appreciated.

A generic error occurred in GDI+ asp.net c#

I need to save base64string to image in local path. The following are the code I used.
byte[] bytes = Convert.FromBase64String(hdnBase64.Value.Split(',')[1]);
System.Drawing.Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = System.Drawing.Image.FromStream(ms);
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
//image.Save("C:\\test.png");
}
string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string path = Path.Combine(Server.MapPath("~/Temp"), filename + ".png");
image.Save(path);
imgBrowse.Attributes.Add("src", path);
hdnBase64 is a hiddenfield which contain base64 image. while executing I got the generic error. please help me out to solve this problem!
Thanks in advance,
Ganesh M
You have to include the Save(path) call in the using section.
You've created the image from a MemoryStream object, which is automatically disposed once you exit from the using block.
byte[] bytes = Convert.FromBase64String(hdnBase64.Value.Split(',')[1]);
System.Drawing.Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = System.Drawing.Image.FromStream(ms);
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string path = Path.Combine(Server.MapPath("~/Temp"), filename + ".png");
image.Save(path);
}
imgBrowse.Attributes.Add("src", path);

how to send image as attachment with web service?

I want to add new employee to web service.
The employee photo should be sent as an attachment with the web service.
and sent as a password protected ZIP file.
Create a class for your image and send as a stream as follows,
You have to add the stream conversion for each image and add the details to a list.
in the client side.
Stream stream = (Stream)openDialog.File.OpenRead();
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
BitmapImage bmi = new BitmapImage();
using (MemoryStream ms = new MemoryStream(bytes))
{
bmi.SetSource(ms);
newRow.Thumbnail = bmi;
}
in your service side
string filePath = ConfigurationManager.AppSettings.Get("ImageUploadPath");
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
filePath = filePath + "\\" + picture.FileName + "." + picture.FileType;
if (picture.FileName != string.Empty)
{
fileStream = File.Open(filePath, FileMode.Create);
writer = new BinaryWriter(fileStream);
writer.Write(picture.FileStream);
}

Write Serialized XML String to XML File

I have a decrypted XML string which was sent over the wire to the receiving box where my code resides. Now, I want to write this XML string to an XML file.
Here's the Decrypt method which my code calls to generate this XML string... maybe this needs to be changed?
[Update]: My problem is that I can't see a way to write/create an XML file from a string of XML... I can see samples using a stream, a URL, but that doesn't help me here.
protected string DecryptForm(byte[] encryptedString, byte[] key, byte[] vector)
{
rijndael = new RijndaelManaged();
rijndael.Mode = CipherMode.CBC;
// Create a decryptor to perform the stream transform
ICryptoTransform decryptor = rijndael.CreateDecryptor(key, vector);
string plainText = null;
try
{
//Create the streams used for decryption
using (MemoryStream msStream = new MemoryStream(encryptedString))
{
using (CryptoStream csStream = new CryptoStream(msStream,
decryptor, CryptoStreamMode.Read))
{
using (StreamReader readerStream = new StreamReader(csStream))
{
// Read the decrypted bytes from the decrypting stream
plainText = readerStream.ReadToEnd();
}
}
}
finally
{
// Clear the RijndaelManaged object
if(rijndael != null)
rijndael.Clear();
}
// Return the decrypted string
return plainText;
}
}
xmlDoc = new XmlDocument();
xmlDoc.LoadXML(MyXMLString);
xmlDoc.Save(MyFilePath)

Resources