I am getting the exception as in the Title while sending an image to a java server
Here's the code:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
img.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String imageDataString = new String(Base64.encodeBase64(byteArray));
System.out.println(imageDataString);
dataOutputStream.writeUTF(imageDataString);
dataOutputStream.flush();
Where img is a bitmap file.
Any help will be highly appreciated !
#Sarram follow the code in the blow link, I was sending images in soap request along with other data in the form of base64String the i was converting it into file
blow is the reference of code
Writing decoded base64 byte array as image file
I am using this cool decoder import sun.misc.BASE64Decoder;
Server side can do it like that
String filePath = "/destination/temp/file_name.jpg";
File imageFile = new File(filePath);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(imageFile);//create file
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
BASE64Decoder decoder = new BASE64Decoder();//create decodeer object
byte[] decodedBytes = null;
try {
decodedBytes = decoder.decodeBuffer(imageFileBase64);//decode base64 string that you are sending from clinet side
} catch (IOException e1) {
e1.printStackTrace();
}
try {
fos.write(decodedBytes);//write the decoded string on file and you have ur image at server side
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
Related
I have been working on a project that implements pattern recognition on breathing patterns as a form of communication for speech impaired speakers.
I have an idea of how to do it, but I have a very basic knowledge of Java. I am stuck. I wanted to get the audio data from microphone and store it in an array. In doing so, I can then pass the data and normalise it, extract features from it, and then store the new array in my database.
Please help. Thank you!
First you Should Encode To String
private void encodeAudio(String selectedPath) {
byte[] audioBytes;
try {
// Just to check file size.. Its is correct i-e; Not Zero
File audioFile = new File(selectedPath);
long fileSize = audioFile.length();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(new File(selectedPath));
byte[] buf = new byte[1024];
int n;
while (-1 != (n = fis.read(buf)))
baos.write(buf, 0, n);
audioBytes = baos.toByteArray();
// Here goes the Base64 string
_audioBase64 = Base64.encodeToString(audioBytes, Base64.DEFAULT);
} catch (Exception e) {
DiagnosticHelper.writeException(e);
}
}
Then Decode it in Received Device
private void decodeAudio(
String base64AudioData,
File fileName,
String path,
MediaPlayer mp) {
try {
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(Base64.decode(base64AudioData.getBytes(), Base64.DEFAULT));
fos.close();
try {
mp = new MediaPlayer();
mp.setDataSource(path);
mp.prepare();
mp.start();
} catch (Exception e) {
DiagnosticHelper.writeException(e);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I'm relatively new to android, and I'm trying to modify an android app such that it downloads a profile picture (preferably in PNG) from a URL, and saves it in the com.companyName.AppName.whatever/files. It should be noted that the app was initially created in Unity, and just built and exported.
Here's my initial code:
URL url = null;
try {
url = new URL(playerDO.getProfileURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
InputStream input = null;
try {
input = url.openStream();
} catch (IOException e) {
e.printStackTrace();
}
String fileName = playerDO.getId() + ".png";
FileOutputStream outputStream = null;
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
byte[] buffer = new byte[256];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT: Here's my other code, as suggested by #Ashutosh Sagar
InputStream input = null;
Bitmap image = null;
try {
input = url.openStream();
image = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String fileName = playerDO.getId() + ".png";
FileOutputStream outputStream = null;
File myDir = getFilesDir();
try {
Log.wtf("DIRECTORY", myDir.toString());
File imageFile = new File(myDir, fileName);
if (!imageFile.exists()){
imageFile.createNewFile();
Log.wtf("ANDROID NATIVE MSG: WARN!", "File does not exist. Writing to: " + imageFile.toString());
}
outputStream = new FileOutputStream(imageFile, false);
image.compress(Bitmap.CompressFormat.PNG, 90, outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
Log.wtf("AWWW CRAP", e.toString());
}
}
(It doesn't write either).
Unfortunately, I've had several problems with this. My primary issue is that when it (on the cases that it does) runs, it actually doesn't save anything. I'll go and check com.companyName.AppName.whatever/files directory only to find no such .png file. I will also need it to overwrite any existing files of the same name, which is hard to check when it doesn't work.
My secondary issue is that it fails to take into account delays in internet connection. Although I've put in enough try-catch clauses to stop it from crashing (as it used to), the end result is that it also doesn't save.
How can I improve upon this? Anything I'm missing?
EDIT:
Printing out the directory reveals it should be in:
/data/user/0/com.appName/files/5965e9e4a0f0463853016e2b.png
However, using ES File explorer, the only thing remotely close to that is
emulated/0/Android/data/com.appName/files/
Are they the same directory?
try this first get bitmap image from url
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
and to save bitmap image please check the ans of GoCrazy
Try this
void getImage(String string_url)
{
//Generate Bitmap from URL
URL url_value = new URL(string_url);
Bitmap image =
BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
//Export File to local Directory
OutputStream stream = new FileOutputStream("path/file_name.png");
/* Write bitmap to file using JPEG or PNG and 80% quality hint for JPEG. */
bitmap.compress(CompressFormat.PNG, 80, stream);
stream.close();
}
I'm using apache-commons-sanselan.jar API to remove EXIF content from only JPEG file.
How to remove this content from other file extensions?
BufferedImage image = ImageIO.read(new File("image.jpg"));
ImageIO.write(image, "jpg", new File("image.jpg"));
Metadata isn't read when you read an image. Just write it back. Replace jpg with the extension you want.
Sources:
How to remove Exif,IPTC,XMP data of a png image in Java
How can I remove metadata from a JPEG image in Java?
In addition to #little-child answer
code:
public static void removeExifTag(final String sourceImageFile, final File destinationImageFile) throws IOException, ImageReadException, ImageWriteException {
try (
OutputStream os = new FileOutputStream(destinationImageFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
){
BufferedImage originalImage = ImageIO.read(new File(sourceImageFile));
originalImage.flush();
ImageIO.write( originalImage,"jpg", baos );
byte[] imageInByte = baos.toByteArray();
new ExifRewriter().removeExifMetadata(imageInByte, bos);
baos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ImageReadException e) {
e.printStackTrace();
} catch (ImageWriteException e) {
e.printStackTrace();
}
}
Context
I am adapting parts of an existing project to a gae project. The original project uses FileInputStream and FileOutputStream but since gae doesn't accept FileOutputStream I am replacing them with ByteArrayInputStream and ByteArrayOutputStream. The original code loaded some local files and I replaced those with Datastore Entities that hold the content of those files in one of their properties.
Problem
It mostly seems to work but I get an ArrayIndexOutOfBoundsException in this piece of code:
private byte[] loadKey(Entity file) {
byte[] b64encodedKey = null;
ByteArrayInputStream fis = null;
try {
fis = fileToStreamAdapter.objectToInputStreamConverter(file);
b64encodedKey = new byte[(int) fis.available()];
fis.read(b64encodedKey);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return b64encodedKey;
}
fileToStreamAdapter.objectToInputStreamConverter(file) takes a Datastore Entity and turns the content of one of its properties into a ByteArrayInputStream.
The original code:
private byte[] loadKey(String path) {
byte[] b64encodedKey = null;
File fileKey = new File(path);
FileInputStream fis = null;
try {
fis = new FileInputStream(fileKey);
b64encodedKey = new byte[(int) fileKey.length()];
fis.read(b64encodedKey);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return b64encodedKey;
}
Is there something I'm missing in the differences between FileInputStream and ByteArrayInputStream that could cause this error?
It seems to me that if objectToInputStreamConverter created the ByteArrayInputStream using ByteArrayInputStream(byte[] buf) then it could just return the byte[] argument and save you from the need to read anything more, not to mention all that error handling.
fis.available() is not the size of the input stream, just how much data available in the buffer at this point.
If you need to return bytes from input stream you have to copy it by using something like this:
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int l;
byte[] data = new byte[16384];
while ((l = fis.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, l);
}
buffer.flush();
return buffer.toByteArray();
Or better us IOUtils from commons-io
I'm trying to load a gif from a url to be displayed in an Imageview, store it in the internal storage and then later read it again. But it refuses to either store the image or reading it, not sure which one because I get no exceptions. Loading the image to the imageview works. The first method below (loadImage())
public Bitmap loadImage(String url){
Bitmap bm = null;
URL request;
try {
if(url!=null){
request = new URL(url);
InputStream is = request.openStream();
bm = BitmapFactory.decodeStream(is);
is.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bm;
}
public String writeGifToInternalStorage (Bitmap outputImage) {
try {
String fileName = String.valueOf(Calendar.getInstance().getTimeInMillis());
ByteBuffer byteBuffer = ByteBuffer.allocate(outputImage.getByteCount());
outputImage.copyPixelsToBuffer(byteBuffer);
byteBuffer.flip();
byte[] data = new byte[byteBuffer.limit()];
byteBuffer.get(data);
FileOutputStream fos = ctx.openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(data);
fos.close();
return fileName;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public Bitmap readFileFromInternalStorage(String filename) {
if (filename == null) return null;
FileInputStream fis;
try {
fis = ctx.openFileInput(filename);
return BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
Any ideas of whats wrong?
Your method readFileFromInternalStorage read an encoded image from the file system. This image file should be what you receive from the server.
For that, you need to save the image when you receive it from the server, for example like so:
InputStream is = new BufferedInputStream(request.openStream());
String fileName = String.valueOf(Calendar.getInstance().getTimeInMillis());
FileOutputStream fos = ctx.openFileOutput(fileName, Context.MODE_PRIVATE);
byte[] buffer = new byte[1024];
int red = 0;
while ((red = is.read(buffer)) != -1) {
fos.write(buffer,0, red);
}
fos.close();
is.close();
Then, your image is saved to the disk, and you can open it using your readFileFromInternalStorage method.
Also, if you use HttpClient instead of URL, I wrote a one-liner for downloading a file: Android download binary file problems