save image in a folder on your website without fileupload - android

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.

Related

How to upload image using App42

I have a WebApi project and a Android client, and I need to upload some images from the WebApi using App42, the problem is, in this tutorial, it must have a StringPath, but I dont have a stringPath, because the image is gonna be send by the Android Client for the Api and then Save those images. Do I have to send the image from Android as Base64 and then create a tempFileObject as Bitmap and then put the stringPath?
String name = "MyPic";
String userName = "Nick";
String filePath = " file path from gallery /sd card";
String fileType = "IMAGE";
String description = "This is my holiday pic";
Upload upload = uploadService.UploadFileForUser(name,userName,filePath,fileType,description);
// File will get uploaded in App42 cloud with above snippet.
IList<Upload.File> fileList = upload.GetFileList(); // This will have only single file uploaded above
for (int i = 0; i < fileList.Count; i++)
{
Console.WriteLine("fileUrl is " + fileList[i].GetUrl());
//This will return uploaded file URL
}
If I understood the query then you don't have file saved in the device local file storage. If Yes, then you can use another API which will ask you the InputSteam of the image as parameter.
I hope this helps.

Xamarin Android Convert Byte array to PDF file

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.

File size is always zero when images uploaded to google cloud storage from Android using JSON api

I am using the below code snippet to upload an image to google cloud storage from Android using JSON api. Although I have tested the file size before upload ,which is not zero, the file size becomes zero after upload.
InputStream is = getContentResolver().openInputStream(imageUri); //imageUri is obtained after the image is chosen
Storage storage = getStorage();
//The below three lines are a test to get the file size
Bitmap selectedImage1 = BitmapFactory.decodeStream(is);
byte[] imageByte = Utilities.getBytesFromBitmap(selectedImage1);
int size = imageByte.length;
StorageObject object = new StorageObject().setName("myobject")
.setContentDisposition("attachment");
String contentType = "image/jpeg";
InputStreamContent content = new InputStreamContent(contentType, is);
content.setRetrySupported(true);
Storage.Objects.Insert insert = storage.objects().insert("mybucket.appspot.com", object, content); //bucketname changed
insert.execute();
I have taken a look at most of the related questions in stackoverflow but could not figure out a solution yet.

Android downloading an image

Here i have stored an image by converting as string using 'base64 format' on my server,and i could able to display it in the same way on image view .But now i want download it to my sd card .I can see that some people downloading using 'URL'. But in my case there is no URL.I just converted the image into string and stored and able to display it on imageview by reconverting it.
this is the way i reconverted the string into image
//getting string from server using json parsor
String image=json_data.getString("img");
txt.setText(u);
//converting string to image
byte[] imageAsBytes = Base64.decode(p.getBytes(), 0);
im = (ImageView)this.findViewById(R.id.imageView1);
im.setImageBitmap(
BitmapFactory.decodeByteArray(imageAsBytes, 0,imageAsBytes.length));
Use Image Loader libraries instead of yours.
https://github.com/nostra13/Android-Universal-Image-Loader
https://github.com/bumptech/glide
http://square.github.io/picasso/
THIS SNIPPET SHOULD HELP !
// give any name to file xxx.jpg
File filePath = new File(Environment.getExternalStorageDirectory()+"/name.jpg");
FileOutputStream os = new FileOutputStream(filePath, true);
EDIT
Bitmap x = BitmapFactory.decodeByteArray(imageasbytes , 0 , inageasbytes.length());
x.compress(
Bitmap.CompressFormat.JPEG, 85, os);
os.flush();
os.close();
Also , add the following permission .
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Also if you want to know how to recover it..
String imgFile = Environment.getExternalStorageDirectory() + "/name.jpg";
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile);
Imageview.setimagebitmap(mybitmap);

Android - Getting, saving and retrieving images from URL

I have a database of recipes, each of which has an image.
The database can be updated from a JSON feed. I then need to retrieve any new images for a newly added recipe. I'm having issues getting an image from a URL, saving it and then updating a recipe with that image.
There are a lot of different answers on Stack Overflow and other sites. Often I can get to what I would expect to be a working point. Where images appear to be getting saved, and any debug print outs I add in show what I expect, but I cannot update my ImageView. By that I mean it remains blank.
I'm not sure if my issue is simply a poor attempt to update the ImageView, or a problem when saving the images. This code is a bit sloppy and inefficient at the moment. I've tried 10-15 variations on this from suggested other posts and have had no luck. Any help would be greatly appreciated.
Manifest
/* I have these two set (Not sure both are necessary) */
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Main frontend class
/* Create databaseHelper */
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
/* ImageView to update image of */
ImageView foodpic = (ImageView)findViewById(R.id.foodpic);
/* Check if image is already available in drawable folder */
int resID = this.getResources().getIdentifier(filename, "drawable", "mypackage.name");
if (resID == 0) {
/* If not, call function to retrieve from external storage */
newPic = db.getOutputMediaFile(origFilename);
if(newPic.exists()) {
myBitmap = BitmapFactory.decodeFile(newPic.getAbsolutePath());
foodpic.setImageBitmap(myBitmap);
foodpic.invalidate(); /* Tried with and without this */
}
}
DatabaseHelper function to retrieve image saved from URL
public File getOutputMediaFile(String filename){
/* Dir I'm (attempting) to save and retrieve images from */
File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/Android/data/mypackage.name/Files");
/* Create the storage directory if it does not exist */
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
/* Get file extension */
String[] fileNameSplit = filename.split("\\.");
String extension = fileNameSplit[(fileNameSplit.length-1)];
/* Get filename, remove special chars & make lowercase */
int extensionIndex = filename.lastIndexOf(".");
filename = filename.substring(0, extensionIndex);
filename = filename.toLowerCase(Locale.getDefault());
filename = filename.replaceAll("[^a-z0-9]", "");
/* Re-make filename to save image as */
String mImageName="r"+filename+"."+extension;
/* Get file
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
DatabaseHelper function to save image from URL
- Called per recipe/image added to the database, if image not found in drawable folder.
public static void saveImage(String imageUrl, String destinationFile, String extension) throws IOException {
URL url = new URL (imageUrl);
InputStream input = url.openStream();
try {
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (new File(storagePath,destinationFile));
try {
byte[] buffer = new byte[2048];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
*Formatting.
Store URL as string in DB and display it with Image Loader is more easy, but doesn't work off line ,if ur apps need internet to work, the image loader could be better.
android-loading-image-from-url-http
I ended up using this library.
It's not an ideal solution as I'd have preferred to look through this library, understand it fully and explain it for others who may need a similar answer. But for now, people attempting to do something similar should be able to use this too.
https://code.google.com/p/imagemanager/

Categories

Resources