ASP.NET Image Upload Parameter Not Valid. Exception - c#

Im just trying to save a file to disk using a posted stream from jquery uploadify
I'm also getting Parameter not valid.
On adding to the error message so i can tell where it blew up in production im seeing it blow up on:
var postedBitmap = new Bitmap(postedFileStream)
any help would be most appreciated
public string SaveImageFile(Stream postedFileStream, string fileDirectory, string fileName, int imageWidth, int imageHeight)
{
string result = "";
string fullFilePath = Path.Combine(fileDirectory, fileName);
string exhelp = "";
if (!File.Exists(fullFilePath))
{
try
{
using (var postedBitmap = new Bitmap(postedFileStream))
{
exhelp += "got past bmp creation" + fullFilePath;
using (var imageToSave = ImageHandler.ResizeImage(postedBitmap, imageWidth, imageHeight))
{
exhelp += "got past resize";
if (!Directory.Exists(fileDirectory))
{
Directory.CreateDirectory(fileDirectory);
}
result = "Success";
postedBitmap.Dispose();
imageToSave.Save(fullFilePath, GetImageFormatForFile(fileName));
}
exhelp += "got past save";
}
}
catch (Exception ex)
{
result = "Save Image File Failed " + ex.Message + ex.StackTrace;
Global.SendExceptionEmail("Save Image File Failed " + exhelp, ex);
}
}
return result;
}

Use image converter to load from byte array:
ImageConverter imageConverter = new System.Drawing.ImageConverter();
Image image = imageConverter.ConvertFrom(byteArray) as Image;
http://forums.asp.net/t/1109959.aspx

It seems your stream type is not valid for Bitmap object, try to copy stream to MemoryStream, and give MemoryStream as a parameter of Bitmap
and remove second dispose as #Aliostad mentoined
something like this
public string SaveImageFile(Stream postedFileStream, string fileDirectory, string fileName, int imageWidth, int imageHeight)
{
string result = "";
string fullFilePath = Path.Combine(fileDirectory, fileName);
string exhelp = "";
if (!File.Exists(fullFilePath))
{
try
{
using(var memoryStream = new MemoryStream())
{
postedFileStream.CopyTo(memoryStream);
memoryStream.Position = 0;
using (var postedBitmap = new Bitmap(memoryStream))
{
.........
}
}
}
catch (Exception ex)
{
result = "Save Image File Failed " + ex.Message + ex.StackTrace;
Global.SendExceptionEmail("Save Image File Failed " + exhelp, ex);
}
}
return result;
}

Related

An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll Additional information: Parameter is not valid

i have to display binary image in pictureBox (Winforms Application) but having the exception "Parameter is not valid". below is my code, i searched alot but could not found the desired solution.
ClsCustomerTransaction ct = new ClsCustomerTransaction();
byte[] photo_aray = (byte[])ct.GetPicture().Rows[0][0];
MemoryStream ms = new MemoryStream();
ms.Write(photo_aray, 0, photo_aray.Length);
pictureBox1.Image = Image.FromStream(ms);
The Image is saved in database by following code.
MemoryStream ms = new MemoryStream();
byte[] PhotoByte = null;
pictureBox1.Image.Save(ms, ImageFormat.Png);
PhotoByte = ms.ToArray();
ClsDressImages.Specification = txtSpecification.Text;
ClsDressImages.Img = PhotoByte;
if (ClsDressImages.SaveImage())
{
MessageBox.Show("Successfully saved");
Reset();
}
public class ClsDressImages
{
public static string table;
public static string Specification { get; set; }
public static byte[] Img { get; set; }
public static bool SaveImage()
{
ClsDatabaseManager dbm = ClsDatabaseManager.InitializeDbManager();
bool result = false;
try
{
dbm.Open();
result = dbm.ExecuteNonQuery("INSERT INTO " + table + " VALUES (N'" + Specification + "','" + Img + "')", CommandType.Text).ToBool();
dbm.Dispose();
}
catch (Exception ex)
{
dbm.Dispose();
throw ex;
}
return result;
}
}
Thanks in advance.

Unable to attach image after scanning

I am able to scan the image using wia. After scanning I am trying to attach that scanned image. Below is the code but I am getting following error message:
microsoft.csharp.runtimebinder.runtimebinderexception:cannot perform runtime binding on a null reference.
private async void Button_Click_3(object sender, RoutedEventArgs e)
{
lblLoading_Copy.Content = "Loading . . .";
//lblLoading.Refresh();
await Task.Delay(1000);
try
{
using (var ms = new MemoryStream())
{
var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression();
document.Open();
foreach (System.Drawing.Image aa in obj)
{
MemoryStream msimage = new MemoryStream();
aa.Save(msimage, ImageFormat.Jpeg);
var image = iTextSharp.text.Image.GetInstance(msimage.ToArray());
image.ScaleToFit(document.PageSize.Width, document.PageSize.Height);
document.Add(image);
}
document.Close();
string Path = ConfigurationManager.AppSettings["uploadfolderpath"].ToString();//confige path
string filename = "C3kycDMS" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
//Save using drive name
//File.WriteAllBytes(Path + filename, ms.ToArray());
byte[] test = ms.ToArray();
Service1.Service objService = new Service1.Service();
string result = objService.SaveScanedDocument(test, filename, 0);
if (result == "")
{
MessageBox.Show("File Upload unsuccessfull", "Error!", MessageBoxButton.OKCancel);
lblLoading_Copy.Content = "";
}
else
{
// MessageBox.Show("File Upload successfull", "Success!", MessageBoxButton.OKCancel);
lblLoading_Copy.Content = "";
}
pic_scan.Source = null;
var hostScript = BrowserInteropHelper.HostScript;
hostScript.document.ResponseData(filename);
// return ms.ToArray();
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OKCancel);
lblLoading.Content = "";
}

Read Image as base64 string; Out of memory exception

I'm trying to convert images in a directory as base64 strings. when I test it in local computer it works, but on the server it gives out of memory exception:
here is my method:
private ImageDataViewModel ReadImagesFromDisk(Guid id)
{
List<string> imageList = new List<string>();
ImageDataViewModel imageDataViewModel = new ImageDataViewModel();
string path = HttpContext.Current.Server.MapPath("~/BusinessImages/" + id.ToString());
try
{
if (Directory.Exists(path))
{
var images = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
.ToList();
string fileName = id.ToString();
foreach (var item in images)
{
using (Image image = Image.FromFile(item))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
imageList.Add(base64String);
}
}
}
imageDataViewModel.Id = id;
imageDataViewModel.ImageData = imageList;
return imageDataViewModel;
}
else
{
return null;
}
}
catch (Exception ex)
{
throw ex;
}
}
I don't know how this happens. Is there any way to handle this problem?
byte[] fileBytes = System.IO.File.ReadAllBytes(yourfilepath + fname);
string fileName = yourfilename.Split(new string[] { "/" }, StringSplitOptions.None)[1];
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
try this,
This will return whole file.

Sending an Image in Base64 Format over to an IIS server (hosting C#.net based Web Handler)

I am trying to send an Image from my android device over to an IIS server which is hosting a C#.NET based web handler.
The root problem I am facing now is how do I send it in to the server?
I have converted the image into base64 format but the part in which I have to send it in the HTTP's POST object is where I am facing a dilema.
HttpPost httppost = new HttpPost("http://192.168.1.248/imgup/Default.aspx");
File data2send = new File(image_str);
FileEntity fEntity = new FileEntity(data2send, "binary/octet-stream");
httppost.setEntity(fEntity);
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
In the above snippet^ The line where I send my base64 string image_str cannot be of File type which is obvious.
So, I need something to convert this base64 string in-order to send it over to the server or better if someone can help me out here thoroughly :D
I tried the namevalue pairs way..it din't worked.
The Image I am sending is of ~3KB.
My full activity code:
public class MainActivity extends Activity {
InputStream inputStream;
private class GetRouteInfo extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.img1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
System.out.println("image_str: "+image_str);
nameValuePairs.add(new BasicNameValuePair("image",image_str));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.248/imgup/Default.aspx");
//post.addHeader("zipFileName", zipFileName);
//httppost.addHeader("image",image_str);
File data2send = new File();
//File data2send = new File(image_str);
FileEntity fEntity = new FileEntity(data2send, "binary/octet-stream");
httppost.setEntity(fEntity);
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
//Toast.makeText(MainActivity.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
System.out.println("Response " + the_string_response);
}catch(Exception e){
//Toast.makeText(MainActivity.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
System.out.println("ERROR " + e.getMessage());
System.out.println("Error in http connection "+e.toString());
}
}
catch (Exception e) {
Log.i("SvcMgr", "Service Execution Failed!", e);
}
finally {
Log.i("SvcMgr", "Service Execution Completed...");
}
return null;
}
#Override
protected void onCancelled() {
Log.i("SvcMgr", "Service Execution Cancelled");
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.i("SvcMgr", "Service Execution cycle completed");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.img1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.248/imgup/Default.aspx");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
Toast.makeText(MainActivity.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(MainActivity.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
System.out.println("Error in http connection "+e.toString());
}*/
try {
new GetRouteInfo().execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
System.out.println("contentLength : " + contentLength);
//Toast.makeText(MainActivity.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
if (contentLength < 0){
}
else{
byte[] data = new byte[512];
int len = 0;
try
{
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
inputStream.close(); // closing the stream…..
}
catch (IOException e)
{
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
System.out.println("Result : " + res);
//Toast.makeText(MainActivity.this, "Result : " + res, Toast.LENGTH_LONG).show();
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
}
return res;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Server Side code (in C#.net):
protected void Page_Load(object sender, EventArgs e)
{
if (System.IO.Directory.Exists(Server.MapPath("~/Data")))
{
}
else
{
System.IO.Directory.CreateDirectory(Server.MapPath("~/Data"));
}
if(Request.InputStream.Length !=0 && Request.InputStream.Length < 32768) {
//Request.ContentType = "binary/octet-stream";
Request.ContentType = "text/plain";
Stream myStream = Request.InputStream;
string fName = Request.Params["image"];
byte[] imageBytes = Convert.FromBase64String(myStream.ToString());
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
string fileName = Server.MapPath("~/Data/").ToString() + "try1" + ".jpeg";
image.Save(fileName);
Request.InputStream.Close();
}
else
{
}
}
One of my favourite piece of code.
Android App upload location
I compress the Image (Re size) it just to be save side (Code at the end)
Bitmap bitmap = resizeBitMapImage1(exsistingFileName, 800, 600);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,30, stream);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image_data", Base64.encodeBytes(stream.toByteArray())));
// image_str = null;
stream.flush();
stream.close();
bitmap.recycle();
nameValuePairs.add(new BasicNameValuePair("FileName", FileName));
String url = "http://www.xyz.com/upload.aspx";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response1 = httpclient.execute(httppost);
Log.i("DataUploaderOffline_Image ","Status--> Completed");
ASPX Page Code
Response.ContentType = "text/plain";
string c = Request.Form["image_data"];
string FileName = Request.Form["FileName"];
byte[] bytes = Convert.FromBase64String(c);
System.Drawing.Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = System.Drawing.Image.FromStream(ms);
image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
String Fname = FileName + ".jpeg";
image.Save(Server.MapPath("Image\\" + Fname), System.Drawing.Imaging.ImageFormat.Jpeg);
Response.End();
}
*Resize Code *
public static Bitmap resizeBitMapImage1(String filePath, int targetWidth,
int targetHeight) {
Bitmap bitMapImage = null;
try {
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
double sampleSize = 0;
Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math
.abs(options.outWidth - targetWidth);
if (options.outHeight * options.outWidth * 2 >= 1638) {
sampleSize = scaleByHeight ? options.outHeight / targetHeight
: options.outWidth / targetWidth;
sampleSize = (int) Math.pow(2d,
Math.floor(Math.log(sampleSize) / Math.log(2d)));
}
options.inJustDecodeBounds = false;
options.inTempStorage = new byte[128];
while (true) {
try {
options.inSampleSize = (int) sampleSize;
bitMapImage = BitmapFactory.decodeFile(filePath, options);
break;
} catch (Exception ex) {
try {
sampleSize = sampleSize * 2;
} catch (Exception ex1) {
}
}
}
} catch (Exception ex) {
}
return bitMapImage;
}
You're not actually setting the name/value pair to the POST. You're merely sending the IMAGE as a base64 string.
Try something like this:
httpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> parms;
httpclient = new DefaultHttpClient();
httppost = new HttpPost(Your Url Here);
params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("image", BASE_64_STRING);
httppost.setEntity(new UrlEncodedFormEntity(params);
HttpResponse resp = httpclient.execute(httppost);

c# upload file to stream?

I want the user to upload a file and save it to a stream.
Here is the code so far:
private void Submit_ServerClick(object sender, System.EventArgs e)
{
fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
}
you could do like this
string filePath = uploadFile(fileUploadControl.FileContent);
private string uploadFile(Stream serverFileStream)
{
string filename = ConfigurationManager.AppSettings["FileUploadTempDir"] +
DateTime.Now.ToString("yyyyMMddhhmm") + "_" +
Customer.GetCustomerName(CustomerId).Replace(" ", "_") + ".txt";
try
{
int length = 256;
int bytesRead = 0;
Byte[] buffer = new Byte[length];
// write the required bytes
using (FileStream fs = new FileStream(filename, FileMode.Create))
{
do
{
bytesRead = serverFileStream.Read(buffer, 0, length);
fs.Write(buffer, 0, bytesRead);
}
while (bytesRead == length);
}
serverFileStream.Dispose();
return filename;
}
catch (Exception ex)
{
lblErrorMessage.Text += "An unexpeded error occured uploading the file. " + ex.Message;
return string.Empty;
}
}
i hope it will helps you...
The object that FileUpload.PostedFile returns has an InputStream property you can read the uploaded file data from.
Looks like this one http://support.microsoft.com/kb/323246
string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
string SaveLocation = Server.MapPath("Data") + "\\" + fn;
try
{
File1.PostedFile.SaveAs(SaveLocation);
Response.Write("The file has been uploaded.");
}
catch ( Exception ex )
{
Response.Write("Error: " + ex.Message);
//Note: Exception.Message returns a detailed message that describes the current exception.
//For security reasons, we do not recommend that you return Exception.Message to end users in
//production environments. It would be better to put a generic error message.
}

Categories