Converting Byte[] to stream file asp.net - 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();
}
}

Related

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

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();

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

BinaryReader.ReadBytes returning junk when converted to string

if I try to explain why I need to do what I'm trying to do it will take a long time, but basically it's this: I have FileUpload control for the user to choose a Jpeg file, I make the upload and after it I want to convert that file to bytes and use it as the source of an Image control.
My code is this one:
string fileName = Server.MapPath("~/TempImages") + #"\foto.jpg";
fileUpload1.SaveAs(fileName);
System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fs);
long byteLength = new System.IO.FileInfo(fileName).Length;
byte[] buffer = binaryReader.ReadBytes((Int32)byteLength);
fs.Close();
fs.Dispose();
string valor = System.Text.Encoding.UTF8.GetString(buffer);
img.ImageUrl = "data:image/jpg;base64," + valor;
The byte array is looking ok, but when I convert it to string it's full of unrecognized characters, I have another page where I do the same thing but instead of getting the bytes from the file I get it from a MySql database and using the same System.Text.Encoding.UTF8.GetString and it works withou a problem.
UPDATE
As asked, this is the code I use when retrieving the from the MySql database:
DataView dv = (DataView)SqlDataSource3.Select(DataSourceSelectArguments.Empty);
byte[] buffer = (byte[])dv.Table.Rows[0]["BIN_FOTO"];
string valor = System.Text.Encoding.UTF8.GetString(buffer);
img.ImageUrl = "data:image/jpg;base64," + valor;
The select of this SqlDataSource3 is a simple Select BIN_FOTO from temp_image. I store this value in the database from a webcam capture WPF program, the code I use to convert the image the webcam captured is:
private string ImageToBase64String(System.Drawing.Image imageData, ImageFormat format)
{
string base64;
MemoryStream memory = new MemoryStream();
imageData.Save(memory, format);
base64 = System.Convert.ToBase64String(memory.ToArray());
memory.Close();
memory.Dispose();
return base64;
}
Then I save the base64 variable to the database.
Hope this clarifies my problem
So you want to read the image file and convert to base 64. After your reading code, do this:
string valor = Convert.ToBase64String(buffer);
Your original code was flawed because you're saving the image, as bytes, to the file with this line of code:
fileUpload1.SaveAs(fileName);
That's not saved as base64, so you have to convert it to base 64 after you read it. Your MySql reading worked because the data was converted to base64 before being saved.
By the way, there's no need for the BinaryReader in this code:
System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fs);
long byteLength = new System.IO.FileInfo(fileName).Length;
byte[] buffer = binaryReader.ReadBytes((Int32)byteLength);
fs.Close();
fs.Dispose();
You can write this instead:
byte[] buffer;
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)
{
long byteLength = fs.Length;
buffer = new byte[byteLength];
int bytesRead = fs.Read(buffer, 0, byteLength);
// optional error check to see that you got all the bytes
if (bytesRead != byteLength)
{
// handle error
}
}
string valor = Convert.ToBase64String(buffer);
I've found the problem, looking at the WPF code I used to convert the image to a Base64String. I just created the same function ImageToBase64String and now it works:
string fileName = Server.MapPath("~/TempImages") + #"\foto.jpg";
fileUpload1.SaveAs(fileName);
System.Drawing.Image teste = System.Drawing.Image.FromFile(fileName);
string valor = ImageToBase64String(teste, System.Drawing.Imaging.ImageFormat.Jpeg);
//System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
//System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fs);
//long byteLength = new System.IO.FileInfo(fileName).Length;
//byte[] buffer = binaryReader.ReadBytes((Int32)byteLength);
//buffer = File.ReadAllBytes(fileName);
//fs.Close();
//fs.Dispose();
//string valor = System.Text.Encoding.UTF8.GetString(buffer);
img.ImageUrl = "data:image/jpg;base64," + valor;
But I still don't know what was wrong with my previous code, anyone can clarify?
This solution worked for me:
System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fs);
//Add this--------------------
fs.Seek(0, SeekOrigin.Begin);
//----------------------------
long byteLength = new System.IO.FileInfo(fileName).Length;
byte[] buffer = binaryReader.ReadBytes((Int32)byteLength);
Just add highlighted line.

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);
}

how to upload a bigger file using Blobdata

Good day Everyone,
I am having a problem in uploading a file that is greater than 2mb. In here I use a blobdata (bytBLOBData). Here's the code for reference.
try
{
OpenFileDialog myOPD = new OpenFileDialog();
myOPD.Filter = "Image files (.pdf)|.pdf";
if (myOPD.ShowDialog() == DialogResult.OK)
{
pat = myOPD.FileName;
string sPath = myOPD.FileName;
var fInfo = new FileInfo(sPath);
//Open FileStream to read file
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);
numBytes = fInfo.Length;
bytBLOBData = br.ReadBytes(Convert.ToInt32(numBytes));
MemoryStream memoryStream = new MemoryStream(bytBLOBData);
FileInfo fi = new FileInfo(myOPD.FileName);
String strName = fi.Name;
txtManual.Text = strName;
txtreferencename.Focus();
br.Close();
fStream.Close();
}
}
catch (Exception)
{
validation.ErrorMessage("load");
}
}
I've research about this problem before, some forums told me that I should use a CommandBehavior.SequentialAccess, but I don't get it right. Any help is highly appreciated :)
Thanks,
what are you trying to do ? I don't understand the purpose of your code, and there is no mention to the file upload. If you simply want to upload a file, use WebClient.UploadFile method.

Resources