I am developing an Android App using Xamarin Studio in order to capture a picture and then send it to a web service.
The steps are:
Capture the picture and store it on the phone.
The web service receives an object as argument. This object contains the image in Base64. This is achieved in the following line:
oImagenFace.ImagenDocumento =(string)Base64ToBitmapDrawableConverter.ConvertBack(BitmapFactory.DecodeFile (imagepath));
At this point I am getting an Out of Memory Exception, but I can not resize the image (as explained here http://developer.android.com/training/displaying-bitmaps/load-bitmap.html) because I need it with the original size. The images are about 200Kb.
Did you tried to skip the BitmapFactory.DecodeFile, and convert the whole file into Base64?
Sg. like this:
oImagenFace.ImagenDocumento =(string)Base64ToBitmapDrawableConverter.ConvertBack(imagepath);
If that won't help, I would try to read the file by chunks and convert that parts to Base64.
Upload Image on Web Server using Android / C# {Xamarin}
This is Just Small Piece of Code. it can send any image from Android to your Web
Server.
System.Net.WebClient Client = new System.Net.WebClient();
Client.Headers.Add("Content-Type", "binary/octet-stream");
byte[] result = Client.UploadFile("localhost/FolderName/upload.php", "POST", path);
string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
Here is the PHP Code {upload.php}. Create a Folder name { Uploads } in
your Application.
<?php
$uploads_dir = 'uploads/'; //Directory to save the file that comes from client application.
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES["file"]["tmp_name"];
$name = $_FILES["file"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
?>
Related
I have a large number of images on a Web server that need to be cropped. I would like to automate this process.
So my thought is to create a routine that, given the URL of the image, downloads the image, crops it, then uploads it back to the server (as a different file). I don't want to save the image locally, and I don't want to display the image to the screen.
I already have a project in C#.Net that I'd like to do this in, but I could do .Net Core if I have to.
I have looked around, but all the information I could find for downloading an image involves saving the file locally, and all the information I could find about cropping involves displaying the image to the screen.
Is there a way to do what I need?
It's perfectly possible to issue a GET request to a URL and have the response returned to you as a byte[] using HttpClient.GetByteArrayAsync. With that binary content, you can read it into an Image using Image.FromStream.
Once you have that Image object, you can use the answer from here to do your cropping.
//Note: You only want a single HttpClient in your application
//and re-use it where possible to avoid socket exhaustion issues
using (var httpClient = new HttpClient())
{
//Issue the GET request to a URL and read the response into a
//stream that can be used to load the image
var imageContent = await httpClient.GetByteArrayAsync("<your image url>");
using (var imageBuffer = new MemoryStream(imageContent))
{
var image = Image.FromStream(imageBuffer);
//Do something with image
}
}
I am using this code below but it works only for files under 20 MB, but I know other Telegram bots who bypass this limitation! For example look at #attachbot. It is in Persian language, if you do not know Persian just send a file first, then send a text. It gives you the result and there is a hidden link inside text which causes that image or video preview under the text. So it uses a URL for that large file! So it somehow saved that file on a server and now has a URL to access that large file.
string fileID = up.Message.Video.FileId;
var filePath = bot.GetFileAsync(fileID);
download_url = #"https://api.telegram.org/file/bot" + Token + "/" + filePath.Result.FilePath;
using (WebClient client = new WebClient())
{
client.DownloadFile(new Uri(download_url), #"D:\myFolder\aFileName.mp4");
}
I have a Cordova app that uses a C# webService to communicate with a SQL database.
This works great.
My problem is that I have some pdf documents on the server with the local filePath held in the database and I need to open these in the app.
I have done a similar thing before where the documents had a URL where they could be reached so they just open, but in this case there is no external access to the file.
So my question is this....how do I best get the file from the server to the app to open it?
I don't need to store the file on the device, just open it so it can be read.
I would be really grateful if someone could steer me in the right direction as I have no clue as the best method for achieving what i'm after.
*****UPDATE******
Right, I don't think i'm a million miles away but have a feeling i'm doing something fundamentally wrong.
I'm creating a byte[] using:
byte[] bytes = System.IO.File.ReadAllBytes(filepath);
which produces a really long string.
In the app, I'm getting that string and using the following to reconstitute it as a file:
var bytes = new Uint8Array(data);
saveByteArray("mytest.txt", data);
function base64ToArrayBuffer(base64) {
var binaryString = window.atob(base64);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
return bytes;
}
function saveByteArray(reportName, byte) {
var blob = new Blob([byte], {type: "application/txt"});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
var fileName = reportName;
link.download = fileName;
link.click();
}
This will either create an empty file or a corrupt one.
Can anyone help with this please?
A fresh pair of eyes would be gratefully received.
Thanks
What you could do would be to make a new endpoint in your C# webservice backend, to download the file from this endpoint, to store it locally, and to display it from your app.
Behind the endpoint, it would use the file location from the database, and it would get the file content in a stream from where the pdf is stored. This stream of data would be placed in a json result object as an array of bytes. Finally, your app would have to get this json object, then to build the pdf file from the array of bytes and from the file name.
Hope it helps.
I have a the following setup to send emails from my c# Application :
SmtpClient (under System.Net.Mail namespace) to do the actual sending once everything is in place and set the 'IsBodyHtml' property of the Message object to True
Using the dll from Sautinsoft I convert a simple rtf file which contains the formatting of the email and convert it to a HTML string which I then use as the body of the mail.
It works great just as it is and I have sent a few test emails to myself and all the appropriate formatting is retained. However i am having a problem with images - The dll converts images to a img tag and uses the base 64 format of the image as the data source, this works fine if you view it as a html page, but sending it as the body of you email produces problems. Email clients such as Yahoo don't mind embedded images but Gmail does not play nice with this methodology. The only image that should appear in the emails I'm sending is the signature image located at the bottom of each email. Using signatures in the native Gmail client in your browser poses no problems since the image has a link to a actual file on a server somewhere, but sending emails with signatures via a C# Application seems to be a different story. Any suggestions?
Thank you for your time.
You may consider automating Outlook from a C# application. See How to automate Outlook and Word by using Visual C# .NET to create a pre-populated e-mail message that can be edited. Also you can find a sample code - C# app automates Outlook (CSAutomateOutlook).
If you are talking about RTF2HTML, you may add any images in a separate folder (no include in body of HTML):
string inpFile = #"..\..\..\..\example.docx";
string outFile = Path.GetFullPath(#"Result2.html");
string imgDir = Path.GetDirectoryName(outFile);
RtfToHtml r = new RtfToHtml();
// Set images directory
HtmlFixedSaveOptions opt = new HtmlFixedSaveOptions()
{
ImagesDirectoryPath = Path.Combine(imgDir, "Result_images"),
ImagesDirectorySrcPath = "Result_images",
// Change to store images as physical files on local drive.
EmbedImages = false
};
try
{
r.Convert(inpFile, outFile, opt);
}
catch (Exception ex)
{
Console.WriteLine($"Conversion failed! {ex.Message}");
}
As the result you will see HTML file with linked images in folder.
In my project we need to save the image taken from webcam in a default path using flex 4.6 but giving a default path in flex(saving the image in a default path like C:\temp..) is not possible so we are passing the byte array of that captured image from flex to .ashx page in .net here,image is saving in a default path but imagebytes is not saving(showing that no data in image).If any body knows please let me know.
Finally i got the succeeded in passing the imagebytes from flex to ashx page like below
//Declare a string in script tag(Initialize a string before init() )
[Bindable]public var str64enc:String="";
//creating object for bytearray
[Bindable]public var imgbytes:ByteArray=new ByteArray();
//creating object for bitmapdata
[Bindable]public var picture1:BitmapData=new BitmapData(103,103,true);
**In your code**
var png:PNGEncoder=new PNGEncoder();
imgbytes=png.encode(picture1);
var base64enc:Base64Encoder=new Base64Encoder();
base64enc.encodeBytes(imgbytes);
str64enc=base64enc.toString();
STEP-BY-STEP PROCEDURE:-------
1-Take a base64encoder and encode the bytearray as below:
var base64enc:Base64Encoder=new Base64Encoder();
base64enc.encodeBytes(imgbytes);
2-then assign that base64 encoder object(In this case" base64enc") to string
3-In HTTPSERVICE u need to pass that string like:
<mx:HTTPService id="savepcktdata" method="POST"
url="ur's destination path like..(axis/security/security.aspx)"
result="savepcktdata_resultHandler(event)"
resultFormat="text">
<mx:request>
<Operation>savepcktdata</Operation>
<bytes>
{str64enc}
</bytes>
</mx:request>
</mx:HTTPService>
4- In .aspx page u need to retrieve like:
string str = Convert.ToString(Request.Form["bytes"]);
cocnclusion:In order to pass the image bytes from flex(flash builder 4.6) to dotnet
(visual studio) you need to pass through the base64 string like above code.
Below is the useful link related to this issue
How to pass image from a flex application to a asp net c# web service? asp-net-c-sharp-web-service