I have a web service, which gives me a json having a node named as 'imagedata'. It contains a huge data as a string. When I print this in browser it gives me valid input. Base64 encoded strings ends on '=' character.
I have also tested it using this tag in a html page, and it works perfectly fine.
<img src="data:image/png;base64,MY_BASE64_ENCODED_STRING"/>
Here is my code;
StringBuilder b64 = new StringBuilder(dataObj.getString("imagedata"));
byte[] decodedByte = Base64.decode(b64.toString(), 0);
bitmap = BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
Kindly note that, This code works on smaller image-data but gives bad-base64 exception on larger image-data
Kindly help me out,
Thanks
Why your server give you the base64 encoding?. Base64 it is just communication not to encoding image. If it use for encoding it will make your image file size bigger.IllegalArgumentException mean your image encoding incorrectly formatted or otherwise cannot be decoded.
In my project i just, for now, i use the Base64 for sending image. But it will be change by multipart. But when server forward to the recipient. It just forward the url of image. So i can do simple process the url to Image with this:
public static Image loadImage(String url)
{
HttpConnection connection = null;
DataInputStream dis = null;
byte[] data = null;
try
{
connection = (HttpConnection) Connector.open(url);
int length = (int) connection.getLength();
data = new byte[length];
dis = new DataInputStream(connection.openInputStream());
dis.readFully(data);
}
catch (Exception e)
{
System.out.println("Error LoadImage: " + e.getMessage());
e.printStackTrace();
}
finally
{
if (connection != null)
try
{
connection.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if (dis != null)
try
{
dis.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return Image.createImage(data, 0, data.length);
}
Note this code for J2ME.
Related
I'm able to successfully send, the encoded video byte[](in string) of any size, response from server, but while downloading in mobile i always encounter MemoryOutOfBoundException when the video requested exceeds 3.5mb(approx), otherwise works fine.
The code below is the one I'm currently using.
String image = (encoded byte[] in form of string from server);
byte[] byteImageData = new byte[image.length()];
byteImageData = Base64.decode(image, Base64.DEFAULT);
System.gc();
BufferedOutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
out.write(byteImageData);
out.flush();
} catch (IOException e) {
e.getMessage();
}
finally {
if (out != null) {
out.close();
}
System.gc();
All I need is that the mobile should be capable enough to download atleast 20mb.
Can anyone please help me out to overcome this problem?
I would suggest to use Android's Download Manager https://developer.android.com/reference/android/app/DownloadManager.html
Then Check register for broadcast receiver to listein for file download.
Please check this example: http://blog.vogella.com/2011/06/14/android-downloadmanager-example/
I've a tcp connection and i try to send and receive messages in byte, but I don't know how it work.
Here is my code to send:
public void write(String message) {
try {
byte[] b = message.getBytes("UTF-8");
writer.write(b.toString());
writer.newLine();
writer.flush();
} catch (IOException e) {
Log.e(MainActivity.TAG, "exception", e);
e.printStackTrace();
} catch (Exception e) {
Log.e(MainActivity.TAG, "exception", e);
e.printStackTrace();
}
}
and this for receive
String message = client.reader.readLine();
JSONObject json = new JSONObject(message);
I try again :)
How I can convert the received byte array to string with full unicode for the mysql database? I use charset Utf8m4 for my database.
This is my code
byte[] message = System.Text.Encoding.UTF8.GetBytes(client.reader.ReadLine()); // client.reader.ReadLine() is already a byte[]
string encoded = System.Text.Encoding.UTF8.GetString(message);
JToken token = JObject.Parse(encoded);
My code isn't work. I get:
{"Id":"Test","Content":"hey???"}
byte[] b = message.getBytes("UTF-8");
writer.write(b.toString());
If this is the code you're asking abut, it is senseless. It should of course be
writer.write(message);
At present you're sending something of the form [B#NNNNNNNNNNN, which is the hashcode of a byte array.
I've found a solution, thank's to #EJP.
In java (client side)
writer.write(B64.encode(message)); // message is a string
In C# (server side)
string encoded = System.Text.Encoding.UTF8.GetString(message);
JToken token = JObject.Parse(encoded);
To save the bytes in database i use blob as type.
Encoding.UTF8.GetBytes(bluuub)
To get the bytes from database
byte[] b = (byte[])reader.GetValue(0);
string bluuub = Encoding.UTF8.GetString(b);
I want to download a file from a Server into a client machine. But i want the file to be downloaded from a browser : I want the file to be saved at the Downloads Folder.
Im using the following code to download files.
public void descarga(String address, String localFileName) {
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
// Get the URL
URL url = new URL(address);
// Open an output stream to the destination file on our local filesystem
out = new BufferedOutputStream(new FileOutputStream(localFileName));
conn = url.openConnection();
in = conn.getInputStream();
// Get the data
byte[] buffer = new byte[1024];
int numRead;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
}
// Done! Just clean up and get out
} catch (Exception exception) {
exception.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException ioe) {
// Shouldn't happen, maybe add some logging here if you are not
// fooling around ;)
}
}
It works but unless i specify the absolute path it does not download the file, therefore is useless to use from different clients with different browsers, because the webpage does not even prompts the message that lets the user know that a file is being downloaded. What can i add to get that to work?
Thanks
I am new to android trying to work on uploading image in to server.
Got some sample code from the Internet. But it is showing some error in the line which am not able to handle it. Can any one help me in this case. And the link which is fetch the code is http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/
and the error is getting is
"The method encodeBytes(byte[]) is undefined for the type Base64"
and the corresponding
i have even downloaded base64.java file in the project
There is no encodeBytes in the API. Use encodeToString.
You can use these methods instead
public static String encodeToString (byte[] input, int offset, int len, int flags)
Since: API Level 8
Base64-encode the given data and return a newly allocated String with the result.
Parameters
input : the data to encode
offset : the position within the input array at which to start
len : The number of bytes of input to encode
flags : controls certain features of the encoded output.
Passing DEFAULT results in output that adheres to RFC 2045.
public static String encodeToString (byte[] input, int flags)
Since: API Level 8
Base64-encode the given data and return a newly allocated String with the result.
Parameters
input : the data to encode
flags :controls certain features of the encoded output.
Passing DEFAULT results in output that adheres to RFC 2045.
Whaaaa!
You MUST indent your code!
For every { you open you should space to the right so you'll see better what your code is doing:
This is good:
try {
something();
} catch (Exception e) {
weMessedUp();
if (e == i)
{
lol();
}
}
This is bad:
try {
something();
} catch (Exception e) {
weMessedUp();
if (e == i)
{
lol();
}
}
It's only for reading, your programs will be faster to understand if in one week you want to modify something.
In eclipse to indent, do ctrl + a to select your whole code, then ctrl + i to indent.
This doesn't answer you question but will help others to answer and you to improve your skills.
You can simply open the file as a bytestream and send it as a stream to your httpconnection?
Opening a file as a stream like so:
File inFile = new File(fileName);
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(inFile)
)
);
URL url = new URL("http://www.google.com");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
while ((decodedString = br.readLine()) != null) {
out.write(decodedString);
}
out.close();
This is the implementation for reading a file line by line. Not sure if it will work given the encoding of an image without line breaks, but you should be able to reengineer to stream byte-by-byte without much trouble.
public class UploadImage extends Activity {
InputStream inputStream;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon); ByteArrayOutputStream <span id="IL_AD5" class="IL_AD">stream</span> = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 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://10.0.2.2/Upload_image_ANDROID/upload_image.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
System.out.println("Error in http connection "+e.toString());
}
}
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…..
Toast.makeText(UploadImage.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…..
Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
}
return res;
i have a requirement, i want to take URL of image from user and then convert it to bytes format, and send it my server, i am using tomcat as web-app server and hibernate as ORM tool, i am already written the server side code for saving the incoming bytes into a table using BLOB, but my problem is that how can i convert the image into array of bytes, so that i can send the array to server to process further.
And adding to above, i can load the data, from table, and then can send the bytes back to client, but how to convert the bytes back to image.
Currently, i am using HTML at client side for web pages and Servlets for request and response.
Please help me.
If it's an image URL, then just read the URL straight into a byte array, like this:
public static byte[] getBytesFromURL(URL url) throws IOException {
InputStream in = null;
ByteArrayOutputStream out = null;
try {
in = url.openStream();
out = new ByteArrayOutputStream();
int len;
byte[] buf = new byte[1024 * 4];
while ((len = in.read(buf)) >= 0) {
out.write(buf, 0, len);
}
byte[] bytes = out.toByteArray();
return bytes;
} catch (IOException e) {
throw e;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
Check the ImageIO class in java. It has methods for both reading and writing images. For more information check here.
It seems that you dont need to do any special computation on your images. Just store them and send them back to a browser. If this is the case, you dont actually need to treat them as images, you can just handle them as java.io.File. Then you can store them as BLOB in your database.
To help you manage the upload you can use commons-fileupload. Or if you are using SpringMVC, have a look at the Multipart Resolver.