My current method of converting the image's bitmap to a byte array to a string crashes the application. The code is below
sampleIV.BuildDrawingCache();
Bitmap bm = sampleIV.DrawingCache;
byte[] finalData;
using (var stream= new MemoryStream())
{
bm.Compress(Bitmap.CompressFormat.Png, 0, stream);
finalData = stream.ToArray();
}
addBook.image =finalData;
await booksTable.InsertAsync(addBook);
If the line is removed then it does work so this is the problem does anybody have a solution for uploading a photo to an azure table.
EDIT:
New code with now converting to base 64 string which does have a length less than 500,000 and a breakpoint in the catch is being reached.
sampleIV.BuildDrawingCache();
Bitmap bm = sampleIV.DrawingCache;
byte[] finalData;
using (var stream = new MemoryStream())
{
bm.Compress(Bitmap.CompressFormat.Png, 0, stream);
finalData = stream.ToArray();
}string s = Convert.ToBase64String(finalData);
addBook.image = s;
try
{
await booksTable.InsertAsync(addBook);
}
catch (Exception)
{
int x = 45;
}
Related
I am trying to upload multiple images to my node server via Android Studio. However the image file always seems to be corrupt on the server. I am able to take and preview the picture in Android but not able to store it on my server.
Here is my server code
app.post('/upload', function(req, res) {
var base64Data = req.rawBody;
fs.writeFile("test.jpg",base64Data,'base64',function(err,written){
if(err) console.log(err);
else {
console.log("file Succesfully written ");
cloudinary.uploader.upload("test.jpg", function (image) {
if(image !== undefined) {
res.json({link: image.secure_url}).end();
console.log("url = " , image.secure_url);
// fs.unlink(ImageFile);
} else console.log.error("Error uploading to Cloudinary, ", image);
});
}
});
});
Here is my front end code I use to convert my bitmap to an encoded Base64 String.
final String encodedString = ImageBase64.encode(fileArray.get(i));
Here is a log of what encodedString holds after being set. Obviously the full value is not displayed.
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAMgA+gDASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
However on my backend it is displayed as this
2F9j%2F4AAQSkZJRgABAQAAAQABAAD%2F2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB%0AAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH%2F2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB%0AAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH%2FwAARCAMgA%2BgDASIA%0AAhEBAxEB%2F8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQ
If you get it url encoded then you should url decode it.
InputStream imageStream;
try {
imageStream = getContentResolver().openInputStream(uri);//uri is the image URI
Bitmap bm = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] byteArray = baos.toByteArray();
String encodedImage = Base64.encodeToString(byteArray,Base64.NO_WRAP);//encodedImage is your image string
} catch (FileNotFoundException e) {
e.printStackTrace();
}
I got bad request 400 when i send base64 image in the web service,
I put base64 string to JSON and POST it using retrofit. here is my code
Bitmap bm = BitmapFactory.decodeFile("IMAGE PATH");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 50, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String imgbase64 = Base64.encodeToString(byteArray, Base64.NO_WRAP + Base64.URL_SAFE);
And add to JSONObject
JSONObject jo = new JSONObject();
try {
jo.put("id",users.get(counter).getId());
jo.put("firstname",users.get(counter).getFirstname());
jo.put("middlename",users.get(counter).getMiddlename());
jo.put("lastname",users.get(counter).getLastname());
jo.put("suffix",users.get(counter).getSuffix());
jo.put("image",imgbase64);
jo.put("date_registered",users.get(counter).getDate_registered());
} catch (JSONException e) {
e.printStackTrace();
}
And I will send it using retrofit
ServiceInterface si = RestClient.getClient();
Observable<Response> call = si.postUser(jo.toString());
Image size is 200kb and i got an error bad request
but when my image size is only 10kb it works fine.
please help.
Try to use Below solution for decode the image and send
Bitmap bitmap;
String encodedString ="";
String filepath=""; // your uploaded image file path
try {
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 1;
bitmap = BitmapFactory.decodeFile(filepath, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedString = Base64.encodeToString(byte_arr, 0);
} catch (Exception e) {
e.printStackTrace();
}
You can put encodedString to the your JSON.
Here is the PHP webservice for decode and upload image to server, also perform your operation to database.
<?php
include('../db/config.php');
// Get image string posted from Android App
$base=$_REQUEST['image'];
// Get file name posted from Android App
$filename = $_REQUEST['filename'];// this your image filename like testimage.jpg
//other files
$id= $_REQUEST['id'];
$firstname = $_REQUEST['firstname'];
$middlename = $_REQUEST['middlename'];// add your parameter
// Decode Image
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
// Images will be saved under 'www/imgupload/uplodedimages' folder
$file = fopen('uploads/'.$filename, 'wb');
// Create File
fwrite($file, $binary);
fclose($file);
// echo 'Image upload complete, Please check your php file directory';
if(isset($filename) && $filename !=''){
$fileUrl = "http://yourdomain/android/upload/".$filename;
}else{
$fileUrl = '';
}
$sql=mysql_query("INSERT INTO tbl_name(Id,firstName,middleName,FileUrl) VALUES ('$Id','$firstName','$middleName','$fileUrl')");
?>
I suggest to try to use this solution, It will work.
I am getting this image as a byte array. So I encode the bytearray and store it in db. Later decode this byte array and saved it in sd card. Issue is that, I am not able to load this image into image view. It tells, skia--> decoder decode false. The bytearray could not be converted to bitmap. Here is the code I used to convert the bytearray to bitmap
Infact, not even able to open the image in Imagebrowser in android device (I have tried in Es Image browser also). But, this image if I open with chrome browser or HTML viewer, it opens flawlessly.
byte[] byteArray= android.util.Base64.decode(in.getBytes(), android.util.Base64.DEFAULT);
if (byteArray != null) {
Log.d(Utilities.class.getSimpleName(), byteArray.toString() + "byteArray Length-->" + byteArray.length);
} else {
Log.d(Utilities.class.getSimpleName(), "byteArray is null");
}
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
Encoding code :
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = conn.getInputStream();
byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
int n;
while ( (n = is.read(byteChunk)) > 0 ) {
baos.write(byteChunk, 0, n);
}
}
catch (IOException e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
e.printStackTrace ();
// Perform any other exception handling that's appropriate.
}
finally {
if (is != null) { is.close(); }
}
response.append(Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT));
Here is the base64 string which I get
Base64 string of image
Can anyone help me is sorting out this issue.
I have to send to a server a few JPEG files taken form camera. Of course they are to big to do it simply by file stream. My code (for each file) looks as follow:
struct3.put("type", "image/jpeg");
f = new File(fileName);
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buffer = new byte[(int)f.length()];
bis.read(buffer);
fis.close();
struct3.put("bits", buffer);
After all I send a struct:
Object[] params3 = { bid, login, pass, struct3 };
Object response2 = client.send("my_function", params3);
When I send small files all is correct, but when files are bigger I received "Out of Memory Exception".
My solution of that is to compress JPEG files:
struct3.put("type", "image/jpeg");
final Options opts = new Options();
opts.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeFile(fileName, opts);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] byteArray = stream.toByteArray();
struct3.put("bits", byteArray);
Object[] params3 = { bid, login, pass, struct3 };
Object response2 = client.send("my_function", params3);
But that way produced an error ON THE SERVER SIDE:
"Premature End of JPEG file".
Is there any way to correct the JPEG file before sending it?
I know that JPEG shoud end with EOI ( 0xff, 0xfd).
How to check it and make a corrections?
There is no log cat report due to photos are uploaded to WordPress and only track is warning from gdlib. The warning contains: "Premature End of JPEG file"
Although I solved the problem. I've implemented procedure checking if byteArray ends with 0xFF,0xD9 and in case is not I add two bytes:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] byteArray = stream.toByteArray();
int byteToSendSize = byteArray.length;
boolean proper = ((byteArray[byteArray.length-2])==((byte)0xff))
&& ((byteArray[byteArray.length-1])==((byte)0xd9));
if(!proper)
byteToSendSize +=2;
byte[] byteToSend = new byte[byteToSendSize];
for (int i = 0; i < byteArray.length; i++) {
byteToSend[i] = byteArray[i];
}
if(!proper){
byteToSend[byteArray.length] = (byte) 0xff;
byteToSend[byteArray.length+1] = (byte) 0xd9;
}
struct3.put("bits", byteToSend);
I am trying to download images from a remote server, the number of images downloaded is 30. The code i am using to download image is as below. Some images download successfully and some images don't download and raises the above exception. What might be the problem.
public static Bitmap loadBitmap(String url)
{
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), 4*1024);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, 4 * 1024);
int byte_;
while ((byte_ = in.read()) != -1)
out.write(byte_);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e("","Could not load Bitmap from: " + url);
} finally {
try{
in.close();
out.close();
}catch( IOException e )
{
System.out.println(e);
}
}
return bitmap;
}
Please look on my this post
Image download code works for all image format, issues with PNG format rendering
In my case I solved this error with encode the url
Because image url that i wanted to download has the Persian letters(or other Unicode character) in it
So I replaced all Persian characters with encoded UTF-8 letters