I would like convert Byte array to PDF file and stored it to Internal Storage. I am using below mentioned code, it is saying PDF is of invalid format.
private void ConvertToFile(string fileName , string filePath,Byte[] Bytes){
if (!File.Exists (filePath)) {
File.WriteAllBytes(filePath, Bytes);
}
}
First you get bytedata from your webservice in your application. then give the respective Absolute path (I have set internal storage path in download folder in my code below). After that WriteAllBytes is the inbuilt function that convert your bytes to pdf here :
WebService ws= new Android.WebService();
byte[] getbytedata= ws.YourMethodName();
string directory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
string file = Path.Combine(directory, "temp.pdf");
System.IO.File.WriteAllBytes(file, getbytedata);
Hope this will work.
Related
I have to export files from my application and looking for a solution, where I can save files, to give the user the possibility to open them.
I tried already getFilesDir().getPath() which worked well, until I realized that the folder can't open from a real device (/data/user/0/com.myapplication.example/files) since the /data path is just a storage area for the application.
What are the alternatives?
You should have a look here https://developer.android.com/training/data-storage
I'm not sure what file type you are trying to store however what you have tried stores the file withing the applications directory and not the devices. To combat this I would look under either Media or Documents and other files again in the above link. I would be able to be of further assistance if I knew what file type you are trying to store. Hope this helps you in some way.
This is a function to store a float array to the phone external storage. Pass the file name.extension in the String name. You could modify it to export your file.
public static void save(float[] input_array, String name)
{
final String TAG2 = "->save()";
String string_array = Arrays.toString(input_array);
String fullName = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder/" + name;
String path = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder";
File folder = new File(path);
if(!folder.exists())
{
folder.mkdirs();
}
BufferedWriter buf;
try
{
buf = new BufferedWriter(new FileWriter(fullName));
buf.write(string_array,0,string_array.length());
buf.close();
Log.d(TAG+TAG2, "array saved as document. ");
}
catch (IOException e)
{
Log.e(TAG+TAG2, "problems while saving the file. ");
}
}
The suggestion with getExternalStorage().getPath() (Thanks to blackapps) helped me to save the pdf in a folder, which can be opened in the file manager.
i have created xamarin form app for signpad which capture sign and saving png file to device storage but file is not writing on storage
here is my code to convert image to bytes[]
var image = await signature.GetImageStreamAsync(SignaturePad.Forms.SignatureImageFormat.Png);//getting png file from here
var signatureMemoryStream = image as MemoryStream;
byte[] data = signatureMemoryStream.ToArray();// convert png to bytes[]
string fileName = "img.png";
DependencyService.Get<IFileReadWrite>().WriteData(fileName, data);
I have created DependencyService (Interface) for saving file
public interface IFileReadWrite
{
void WriteData(string fileName, byte[] data);
}
This is my code to save file using native(app.android) api
public class FileHelper : IFileReadWrite
{
public void WriteData(string filename, byte[] data)
{
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var filePath = Path.Combine(documentsPath, filename);
File.WriteAllBytes(filePath, data); // this execute without error but file is not saving on path
}
}
i already have given permission WRITE_EXTERNAL_STORAGE in mainfest
Replace this in your code and try:
var documentsPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
Hope this may solve your issue.
i have my website hosted on a server and i have a folder their named images.I am recieving a base64 string and convert it into an image and saving it in my local directory and it works perfectly.
[WebMethod]
public void UploadPics(String imageString)
{
//HttpRequest Request = new HttpRequest();
//HttpPostedFile filePosted = new HttpPostedFile();
string base64String = imageString;
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
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 newFile = Guid.NewGuid().ToString() + fileExtensionApplication;
string filePath = "C:/Users/MUWebServices/App_Code/images/pic1.jpg";
image.Save(filePath, ImageFormat.Jpeg);
}
But when i use
string filePath = "http://mywebsite.com/images/pic1.jpg";
image.Save(filePath, ImageFormat.Jpeg);
received following exception
"System.ArgumentException: URI formats are not supported" .
How can i save images on website folder. I found some solutions but all were using fileUpload and i can't use that because i am receiving base64 image string from android and using this webservice to save images.
You will have to upload the file. Since you are opening a TCP/IP connection to another computer you need to follow protocol to write that file to that remote directory. Let me explain this to you as Robert A. Heinlein
once said,
Anyone who considers protocol unimportant has never dealt with a cat. -Robert A. Heinlein
Jokes apart you still have to use file upload(you could do this via AsyncTask. A remote computer will most probably not use a uri for the same.
Im new to android development and trying to get metadata of image using ExifInterface. I stored the image under drawable and trying to get the metadata but getting null values for all fields(date, imagelength, imagewidth). I tried to access image path as this :
String path = "drawable://" + R.drawable.testimage;
and provided this path to ExifInterface.
ExifInterface exif = new ExifInterface(path);
I dont know if storing image under drawable is correct or not because when I run the app in emulator I get something like this :
E/JHEAD﹕ can't open 'drawable://2130837561'
So if this is wrong then please tell me where should I store the image and how to provide image path to ExifInterface.
Thank you in advance.
To get a drawable, you can you this snippet:
Drawable drawable = getResources().getDrawable(android.R.drawable.your_drawable);
I'm not sure if your way is correct, as I've never seen it like that. Do you really need the path to your image to use it on that ExifInterface class?
Ok, I did some digging and found this question, which led me to this one. As it seems, you can not get an absolute path from a resource inside your apk. A good solution would be for you to save it as a file on the external memory, and then you can get the path you want.
First of all, add this to your AndroidManifest.xml, so your app can write to the cellphone memory:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Ok, to save it you can try this, first create a bitmap from your drawable resource:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.your_drawable);
After that get the path you want to save your images, and put it on a String. More info on that here.
The Android docs have a good example on how to get the path. You can see it here.
To keep it simple, I'll copy and paste the snippet from the docs.
void createExternalStoragePrivateFile() {
// Create a path where we will place our private file on external
// storage.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
try {
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(R.drawable.balloons);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
void deleteExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
if (file != null) {
file.delete();
}
}
boolean hasExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
if (file != null) {
return file.exists();
}
return false;
}
After that, get the path of the file you saved on the external memory, and do as you wish.
I'll keep the old example as well. You can use the method getExternalStorageDirectory() to get the path, or getExternalCacheDir(). After that, you can use File method called getAbsolutePath() to get your String.
String path = (...) // (you can choose where to save here.)
File file = new File(path, "your_drawable.png");
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // You can change the quality from 0 to 100 here, and the format of the file. It can be PNG, JPEG or WEBP.
out.flush();
out.close();
For more info on the Bitmap class, check the docs.
If you need more info, let me know and I'll try to show more samples.
EDIT: I saw your link, and there was this snippet there:
//change with the filename & location of your photo file
String filename = "/sdcard/DSC_3509.JPG";
try {
ExifInterface exif = new ExifInterface(filename);
ShowExif(exif);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, "Error!",
Toast.LENGTH_LONG).show();
}
As you can see, if you really want to see the exif data of a internal image resource, you'll have to save it somewhere else, and then you can try to get the absolute path for that File, then, call the method to show the exif.
How to compare one image token with camera with all the other images stored in the sd card and display the result?
public class SearchForFaces extends Activity {
Bitmap bitmapOriginale;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b1 = getIntent().getExtras();
String cin= b1.getString("cin");
//getting the image
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/Student");
File file = new File(directory, cin+"jpg");
try {
FileInputStream streamIn = new FileInputStream(file);
bitmapOriginale = BitmapFactory.decodeStream(streamIn);
streamIn.close();
} catch (IOException e) {
Log.d("SearchForFaces Exception", e.getMessage());
}
if(bitmapOriginale.sameAs(//images from sdcard))
{
//display founded image
}
}
}
i think, its not necessary read all images..if you want compare images from camera, you can "easy" take the images in DCMI folder. But ok, user will move some files in another folder. So in that case i will advice just open first folder, read files in there and check the format, after that open another folder, read files in there and again check the formats and save the paths to the jpg files.
So in this case just easy some for, foreach, while cykl or you can do it with recursion.
You will have some ArrayList (linkedList, whatever) and in this list you can put the paths. Then just call your sameAs method.
On this you can use Environment.getExternalStorageDirectory().listFiles();
But..i am not sure if your "algorithm" will work..image recognition is really hard part of computer science..and if you dont know how to get the files on SDcard..the algorithm wouldnt probably work..
But if you want to check the similarity with byte by byte comparsion, then its ok..
Check also this blog http://mihaifonoage.blogspot.com/2009/09/displaying-images-from-sd-card-in.html It shows how to read an images from sd card. Once you read them you can use your sameAs() written method to compare them.