Unable to attach image after scanning - c#

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 = "";
}

Related

How do I delete/replace an image in a PDF file without breaking the file, using iTextsharp and C#

I'm trying to insert an image with id into a PDF document and allow to replace it later with another image.
My process is as follows:
Get an image from the client (with a unique ID).
Try to find an existing image with the same ID, in the PDF document.
If I find an existing image, try to delete it and put the new image instead, or try to replace the existing image with the new one. (tried both).
If I don't find an existing image, insert the image in a position I choose.
I use code from Bruno Lowagie book:
Replacing
Adding image
The problem is that whenever I delete an existing image or replace it my document gets corrupted. What am I doing wrong?
This is the code:
public static bool PdfInsertSignature(string path, string fileName, string signatureName, byte[] imageBytes)
{
bool resultOk = true;
string tmpFilename = string.Concat("tmp_", Guid.NewGuid().ToString(), ".pdf");
// get file, copy to new file with signature
using (Stream inputPdfStream = new FileStream(path + fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream outputPdfStream = new FileStream(path + tmpFilename, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (var reader = new PdfReader(inputPdfStream))
using (PdfStamper stamper = new PdfStamper(reader, outputPdfStream, '\0', false))
{
var img = System.Drawing.Image.FromStream(new MemoryStream(imageBytes));
Image image = Image.GetInstance(img, BaseColor.WHITE);
img.Dispose();
var positions = stamper.AcroFields.GetFieldPositions(signatureName)[0];
if (positions != null)
{
//DeleteExistingSignatureImage(reader, stamper, signatureName);
image.SetAbsolutePosition(positions.position.Left + 20, positions.position.Top - 15);
image.ScalePercent(0.2f * 100);
image.BorderWidth = 0;
PdfImage pdfImg = new PdfImage(image, "", null);
pdfImg.Put(new PdfName("ITXT_SigImageId"), new PdfName(signatureName + "_img"));
if (!ReplaceImage(reader, stamper, signatureName, pdfImg))
{
PdfIndirectObject objRef = stamper.Writer.AddToBody(pdfImg);
image.DirectReference = objRef.IndirectReference;
PdfContentByte pdfContentByte = stamper.GetOverContent(positions.page);
pdfContentByte.AddImage(image);
}
}
else
{
resultOk = false;
logger.Error($"No matching Signature found for signatureName: {signatureName} in fileName: {fileName}.");
}
}
}
if (resultOk)
{
// delete old file and rename new file to old file's name
File.Delete(path + fileName);
File.Move(path + tmpFilename, path + fileName);
}
else
{
File.Delete(path + tmpFilename);
}
return resultOk;
}
private static bool ReplaceImage(PdfReader reader, PdfStamper stamper, string signatureName, PdfStream newImgStream)
{
PdfName key = new PdfName("ITXT_SigImageId");
PdfName value = new PdfName(signatureName + "_img");
PdfObject obj;
PRStream stream;
for (int i = 1; i < reader.XrefSize; i++)
{
obj = reader.GetPdfObject(i);
if (obj == null || !obj.IsStream())
{
continue;
}
stream = (PRStream)obj;
PdfObject pdfSubtype = stream.Get(PdfName.SUBTYPE);
if (pdfSubtype != null && pdfSubtype.ToString().Equals(PdfName.IMAGE.ToString()))
{
var streamVal = stream.Get(key);
if (streamVal != null && value.Equals(streamVal))
{
stream.Clear();
var ms = new MemoryStream();
stream.WriteContent(ms);
stream.SetData(ms.ToArray(), false);
foreach (PdfName name in newImgStream.Keys)
{
stream.Put(name, stream.Get(name));
}
return true;
}
}
}
return false;
}
private static void DeleteExistingSignatureImage(PdfReader reader, PdfStamper stamper, string signatureName)
{
PdfName key = new PdfName("ITXT_SigImageId");
PdfName value = new PdfName(signatureName + "_img");
PdfObject obj;
PRStream stream;
for (int i = 1; i < reader.XrefSize; i++)
{
obj = reader.GetPdfObject(i);
if (obj == null || !obj.IsStream())
{
continue;
}
stream = (PRStream)obj;
PdfObject pdfSubtype = stream.Get(PdfName.SUBTYPE);
if (pdfSubtype != null && pdfSubtype.ToString().Equals(PdfName.IMAGE.ToString()))
{
var streamVal = stream.Get(key);
if (streamVal != null && value.Equals(streamVal))
{
stream.Clear();
PdfReader.KillIndirect(stream);
//PdfReader.KillIndirect(obj);
//reader.RemoveUnusedObjects();
}
}
}
}
The purpose of signing a PDF file is to prevent further changes without notice.
You need to sign the document after you swap the image, or it will be corrupted.
Just do make it easier to find:
This is Solution provided by amira.
This is the code i've used to replace a 'ButtonField' on my PDF template with a signature image :
string TempStampPath = Server.MapPath(TempPath + "BookingConfirmation.pdf");
PdfReader pdfReader = new PdfReader(TempStampPath);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(LocalFileName, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
try
{
pdfFormFields.SetField("NameSurname", NameSurname);
pdfFormFields.SetField("IdNumber", IDNumber);
pdfFormFields.SetField("CourseName", CourseName);
pdfFormFields.SetField("Location", Venue);
pdfFormFields.SetField("DateCompleted", CourseDate);
pdfFormFields.SetField("FacilitatorName", Facilitator);
try
{
iTextSharp.text.Image signature = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Png);
PushbuttonField ad = pdfStamper.AcroFields.GetNewPushbuttonFromField("btnFacilitatorSignature");
ad.Layout = PushbuttonField.LAYOUT_ICON_ONLY;
ad.ProportionalIcon = true;
ad.Image = signature;
ad.BackgroundColor = iTextSharp.text.BaseColor.WHITE;
pdfFormFields.ReplacePushbuttonField("btnFacilitatorSignature", ad.Field);
}
catch (Exception ex)
{ }
pdfStamper.FormFlattening = true;
pdfStamper.Close();
pdfStamper.Dispose();
pdfReader.Close();
}
catch (Exception ex)
{
pdfStamper.Close();
pdfStamper.Dispose();
pdfReader.Close();
}

how to extract embedded image object from power Point using Microsoft office interop power point

This is the code through I am trying to extract the embedded image from PPT file
using this code and found, how many embedded object in this file
but when i try to extract from it i now extract as its actual from mate
i do not extract embedded image(.JPEG) from PPT file using this code
if any one have idea how to extract image please share your code or link
thanks
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
private void ultraButtonPPT_Click(object sender, EventArgs e)
{
PowerPoint.Application app = new PowerPoint.Application();
// app.Visible = Office.MsoTriState.msoTrue;
PowerPoint.Presentation pptPresentation = null;
//open powerpoint file in your hard drive
pptPresentation = app.Presentations.Open(#"Presentation2.pptx", Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
int j = 1;
foreach (PowerPoint.Slide slide in pptPresentation.Slides)
{
PowerPoint.Shapes slideShapes = slide.Shapes;
//foreach (PowerPoint.Shape shape in slideShapes)
//{
// var shaptype = shape.Type;
// var name = shape.Name;
// if (shaptype == Microsoft.Office.Core.MsoShapeType.msoEmbeddedOLEObject)
// {
// shape.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
// var fileName = #"C:\Harshil\Projects\EmbededExtraction\EmbededFiles\" + j.ToString("00000") + shape.Name;
// string progID = shape.OLEFormat.ProgID;
// MemoryStream memStream = null;
// shape.Copy();
// IDataObject data = Clipboard.GetDataObject();
// var abcx = data.GetType();
// var ddd = data.GetFormats();
// if (data.GetDataPresent(System.Windows.Forms.DataFormats.Bitmap))
// {
// Image image = (Image)data.GetData(System.Windows.Forms.DataFormats.Bitmap, true);
// image.Save(fileName + ".gif", System.Drawing.Imaging.ImageFormat.Gif);
// image.Save(fileName + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
// }
// memStream = (MemoryStream)Clipboard.GetDataObject().GetData("Embedded Object");
// if (progID.Equals("Package"))
// {
// MemoryStream strm = new MemoryStream();
// var adf=shape.OLEFormat.ObjectVerbs;
// foreach(var xxxx in adf)
// {
// }
// try
// {
// //If image is valid image then save it as PNG image
// Bitmap img = (Bitmap)Bitmap.FromStream(strm);
// img.Save(fileName + ".png", ImageFormat.Png);
// }
// catch
// {
// Stream file = new FileStream(name + ".object", FileMode.Create);
// strm.WriteTo(file);
// }
// fileName += ".png";
// }
// if (progID.StartsWith("Word", StringComparison.OrdinalIgnoreCase))
// {
// fileName += ".docx";
// }
// StreamWriter sWriter = new StreamWriter(fileName);
// BinaryWriter bWriter = new BinaryWriter(sWriter.BaseStream);
// byte[] dataBytes = new byte[memStream.Length];
// memStream.Read(dataBytes, 0, (int)memStream.Length);
// bWriter.Write(dataBytes);
// bWriter.Close();
// }
// j++;
//}
for (int index = 1; index <= slide.Shapes.Count; index++)
{
var shaptype = slide.Shapes[index].Type;
var VISIBILITY = slide.Shapes[index].Visible.ToString();
if (shaptype == Microsoft.Office.Core.MsoShapeType.msoEmbeddedOLEObject)
{
if (VISIBILITY.Equals("msoFalse"))
{
slide.Shapes[index].Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
}
string progID = slide.Shapes[index].OLEFormat.ProgID;
MemoryStream memStream = null;
slide.Shapes[index].Copy();
memStream = (MemoryStream)Clipboard.GetDataObject().GetData("Embedded Object");
string fileSavePath = #"C:\Harshil\Projects\EmbededExtraction\EmbededFiles\" + j.ToString("00000") + slide.Shapes[index].Name;// + ".jpg";
if (progID.Equals("Package"))
{
fileSavePath += ".png";
}
if (progID.StartsWith("Word", StringComparison.OrdinalIgnoreCase))
{
fileSavePath += ".docx";
}
if (progID.StartsWith("paint", StringComparison.OrdinalIgnoreCase))
{
fileSavePath += ".jpg";
IDataObject data = Clipboard.GetDataObject();
Image image = (Image)data.GetData(System.Windows.Forms.DataFormats.Bitmap, true);
image.Save(fileSavePath + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
continue;
}
StreamWriter sWriter = new StreamWriter(fileSavePath);
BinaryWriter bWriter = new BinaryWriter(sWriter.BaseStream);
byte[] dataBytes = new byte[memStream.Length];
memStream.Read(dataBytes, 0, (int)memStream.Length);
bWriter.Write(dataBytes);
bWriter.Close();
}
if (shaptype == Microsoft.Office.Core.MsoShapeType.msoPicture)
{
// string progID = slide.Shapes[index].OLEFormat.ProgID;
if (VISIBILITY.Equals("msoFalse"))
{
slide.Shapes[index].Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
}
var visibale = slide.Shapes[index].Visible;
slide.Shapes[index].Copy();
System.Drawing.Image image = (System.Drawing.Image)Clipboard.GetDataObject().GetData("Bitmap");
// using (var newImage = ScaleImage(image, 300, 400))
{
string fileSavePath = #"C:\Harshil\Projects\EmbededExtraction\EmbededFiles\" + index + j.ToString("00000") + slide.Shapes[index].Name + ".png";
image.Save(fileSavePath);
}
}
}
j++;
}
pptPresentation.Close();
}

File Stream not return after closing it in finally block C#

I have download files by returning as stream like below using WCF rest service.
Stream stream = null;
var directoryInformation = CommonServices.Utility.DirectoryHelper.GetTempFolderRootLocation();
string newFolderPath = directoryInformation + "\\Attachments\\" + Guid.NewGuid();
try
{
Directory.CreateDirectory(newFolderPath);
DataSet getDocumentContent = GetDocumentContent(engagementId, documentId);
var fileName = getDocumentContent.Tables[0].Rows[0]["Fullname"] as string;
var byteData= getDocumentContent.Tables[0].Rows[0]["FilestreamContent"] as byte[];
string fullPath = newFolderPath + "\\" + fileName;
using (var fileStream = new FileStream(fullPath, FileMode.Create))
{
if (byteData != null)
{
fileStream.Write(byteData,0,byteData.Length);
fileStream.Close();
}
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
WebOperationContext.Current.OutgoingResponse.Headers.Add("content-disposition","inline; filename=" + fileName);
}
}
stream = File.OpenRead(fullPath);
return stream;
}
catch (Exception exception)
{
return null;
}
The above code works perfectly and can download the file in browser. But i have to delete the file after return the stream. So i have try to close and delete the file including the directory in finally block like below
finally
{
if (stream != null) stream.Close();
Directory.Delete(newFolderPath, true);
}
Full Method code
public Stream DownloadAttachment(string engagementId, string documentId)
{
Stream stream = null;
var directoryInformation = CommonServices.Utility.DirectoryHelper.GetTempFolderRootLocation();
string newFolderPath = directoryInformation + "\\Attachments\\" + Guid.NewGuid();
try
{
Directory.CreateDirectory(newFolderPath);
DataSet getDocumentContent = GetDocumentContent(engagementId, documentId);
var fileName = getDocumentContent.Tables[0].Rows[0]["Fullname"] as string;
var byteData= getDocumentContent.Tables[0].Rows[0]["FilestreamContent"] as byte[];
string fullPath = newFolderPath + "\\" + fileName;
using (var fileStream = new FileStream(fullPath, FileMode.Create))
{
if (byteData != null)
{
fileStream.Write(byteData,0,byteData.Length);
fileStream.Close();
}
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
WebOperationContext.Current.OutgoingResponse.Headers.Add("content-disposition","inline; filename=" + fileName);
}
}
stream = File.OpenRead(fullPath);
return stream;
}
catch (Exception exception)
{
return null;
}
finally
{
if (stream != null) stream.Close();
Directory.Delete(newFolderPath, true);
}
}
After adding this code file is not downloaded in client.Is there any way to delete the file?Please help me to resolve this
You can delete the file in OperationContext.OperationCompleted as shown in http://devdump.wordpress.com/2008/12/07/disposing-return-values/
OperationContext clientContext = OperationContext.Current;
clientContext.OperationCompleted += new EventHandler(delegate(object sender, EventArgs args)
{
if (stream != null) stream.Close();
Directory.Delete(newFolderPath, true);
});
Change your method to this.
public void DownloadAttachment(string engagementId, string documentId, Action<Stream> processFile)
and instead of returning the stream call the processFile Action
processFile(stream);
This way you're not leaving the method in order to process the file. You will need to restructure the calling code in order to process the file though.

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

ASP.NET Image Upload Parameter Not Valid. Exception

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

Categories