How to get the result of Runtime.getRuntime().exec directly - android

I'm working on a rooted android device. I'm trying to capture the screen and store the result in Bitmap for later usage.
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
path += "/img.png";
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + path).getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
final Bitmap x = BitmapFactory.decodeFile(path);
What I'm doing here is naming a path for a new image and capturing the screen using the command /system/bin/screencap -p FILEPATH. Then I read the image I stored in that file and use it in the bitmap.
My problem with my current code is that it's slow(not suitable for a real-time application). I'm now trying to make it faster. Instead of saving the captured picture into file and then reading it again from the program, I want to read it directly from the result of Runtime.getRuntime().exec(...)
In the description of the command screencap, I found that I can use it without specifying the output file name, and in this case the results will be printed to stdout.
I tried several codes to read the result byte array to use it directly in my code
final Bitmap x = BitmapFactory.decodeByteArray(resultArrayByte, 0, resultArrayByte.length);
but none of the codes worked with me.
How can I use sh's input/output streams to get the result byte array directly without saving the output into a file then loading it again?

Take a Look here, in this link you can find a library called ASL
a lot of questions in this post, i'm confused :)
i hope this link is useful for your requirements.

Related

Unable to find saved image

I'm very new to Android. I'm working with Xamarin and I have to take a picture with camera and save the picture.
I achieved to take the picture, I have a Bitmap object. Then I save it without error but when I try to find it, there is no file.
There is my code :
Bitmap imgBmp = /* image initialized */
//Save image on folder
var folderPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var filePath = System.IO.Path.Combine(folderPath, "image1.png");
var stream = new System.IO.FileStream(filePath, FileMode.Create);
bool isOK = imgBmp.Compress(Bitmap.CompressFormat.Jpeg, 95, stream);
stream.Flush();
stream.Close();
I have no error when execute, isOK is true but when I search for the image.png I'm unable to find the file.
With debugger I saw that the path is : /data/user/0/com.myCompagny.MyAppli/files/image1.png but I can not see that folder.
Can someone help me to find my image1.png ?
Or to change the default folder to something like Pictures\MyApplication\image.png but I don't know how to find default folder for images.
Your file is there, but you have no permissions to see it. App directories are only readable to the owning app's uid. If you try to find your file through the shell, your uid is different.
You should try to use another folder path if you want to save file in a world readable location.
I'm just guessing but maybe System.Environment.SpecialFolder.CommonPictures would do.

Converting Image To PCL And Printing Via Bluetooth

Problem:
Using an Android device, without internet / network connection, I have to print images to a bluetooth enabled printer.
Be aware that this is the business case — I cannot use Google Cloud Print, nor can I use PrinterShare or anything else like that. The data generated by the app is medical in nature and must be kept confidential and within the app.
What I’ve accomplished:
Generating PCL data (text only, no images) to send to a bluetooth connection that the printer can process and output.
What I’ve tried:
Generating PCL data (image) using the Android ImageMagick port (found here: https://github.com/paulasiimwe/Android-ImageMagick) and sending the generated PCL data to the bluetooth connection.
Result:
Gibberish, but gibberish that appears to be the right dimensions of the image I am trying to print.
==============
My hypothesis is that there’s something slightly off in my implementation of the conversion, but I’m not sure what it is.
Sample Code:
NOTE: this is proof of concept work and captures an image from the Assets dir, makes it available, and then converts it.
// Attempt to get image file from Assets folder
AssetManager assetManager = context.getAssets();
InputStream istr = assetManager.open("test.jpg");
Bitmap bitmap = BitmapFactory.decodeStream(istr);
// Access External Storage Directory and save file
String root = Environment.getExternalStorageDirectory().toString();
File tempDirectory = new File(root + "/temp");
tempDirectory.mkdirs();
String fileName = "test.jpg";
File file = new File (tempDirectory, fileName);
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception exception) {
// Exception found
}
// Capture file of recently saved image, convert to PCL
try{
ImageInfo originalInfo = new ImageInfo(Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp/test.jpg");
MagickImage mImage = new MagickImage(originalInfo);
String newInfoPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp/test.pcl";
mImage.setFileName(newInfoPath);
mImage.setImageFormat("pcl");
ImageInfo newInfo = new ImageInfo(newInfoPath);
mImage.writeImage(newInfo);
} catch (MagickException exception) {
// Exception found
}
I then retrieve the PCL file and send it to the bluetooth connection (using another method that works using standard PCL files), but as mentioned the output is gibberish.
I feel like I’m missing something simple, but I’m just not seeing it.
Also, I am seeing the following in LogCat that may / may not be related, but I haven't been able to find any information about resolving this nor can I determine if it's anything more than a warning.
V/Magick: ThrowException
V/Magick: severity: 395
V/Magick: reason: UnableToOpenConfigureFile `policy.xml' # warning/configure.c/GetConfigureOptions/589
V/Magick: Attempting to read from file /storage/emulated/0/temp/test.jpg
V/Magick: ThrowException
V/Magick: severity: 395
V/Magick: reason: UnableToOpenConfigureFile `magic.xml' # warning/configure.c/GetConfigureOptions/589
V/Magick: OpenPixelCache()
V/Magick: - cache_info->columns: 144
V/Magick: - cache_info->rows: 144
V/Magick: - cache_info->offset: 0
V/Magick: - cache_info->length: 165888
V/Magick: - length: 207360
V/Magick: - create memory pixel cache
V/Magick: ReadImage completed
Does anyone have any experience with this or can anyone point me in the right direction?

How can I open raw image files?

In my application , I am able to read framebuffer data but I cant open the image file ,I dont know why but what I came to know by searching is it is in the raw format .
Can someone tell me how can open this raw format of data on to a human readable image format
My code to get raw image file is as follows
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + ss.getAbsolutePath()).getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
Thanks in advance
If i get your question than try this:-
myIageView.setImageResource(R.raw.imageName);

Android - Best way to convert .gif to .png

Im downloading lots of .gif files from a server and when I try to draw on them in a canvas it never works. Ive created the bitmaps from the gifs and have set them to be immutable using the Options class and have tried just creating a new file and saving the image as a png but that doesnt seem to work either. Does somebody happen to have a good simple way to convert a gif to a png? So far Ive tried:
Bitmap b = BitmapFactory.decodeFile(mediaStorageDir.getAbsolutePath() + "/" +
cr.getString(cr.getColumnIndex(gh.Zone_ZoneName))+".gif");
OutputStream stream = null;
File f = new File(mediaStorageDir.getAbsolutePath() + "/" +
cr.getString(cr.getColumnIndex(gh.Zone_ZoneName))+".png");
if(f.createNewFile()){
System.out.println("PNG CREATED "+f.getAbsolutePath());
}else{
System.out.println("PNG NOT CREATED "+f.getAbsolutePath());
}
stream = new FileOutputStream(f.getAbsolutePath());
b.compress(CompressFormat.PNG, 100, stream);
stream.close();
But this doesnt seem to work. I never even see the system.out.println calls either and I know that the code is being run because right above the gif's are being saved.
I figured out my problem. There was a system lock on the newly created file when I was trying to access it to make a png from it. When I moved the call elsewhere to make the png it worked fine.

Program crashes on trying to open a file

My android program crashes on this line when the file size is very large. Is there any way I can prevent the program from crashing ?
byte[] myByteArray = new byte[(int)mFile.length()];
Additional details :-
I am trying to send a file to server.
error log-
E/dalvikvm-heap(29811): Out of memory on a 136309996-byte allocation.
You should use a stream when reading the file. Since you've mentioned sending to a server, you should stream that file to the server.
As others have mentioned, you should consider your data size (1GB seems excessive). I haven't tested this, but the basic approach in code would look something like:
// open a stream to the file
FileInputStream fileInputStream = new FileInputStream(filePath);
// open a stream to the server
HttpURLConnection connection = new URL(url).openConnection();
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
byte[] buffer = new byte[BUFFER_SIZE]; // pick some buffer size
int bytesRead = 0;
// continually read from the file into the buffer and immediately write that to output stream
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer);
}
Hope that is clear enough for you to fit to your needs.
Yep. Don't try to read the whole file into memory at once...
If you really need the whole file in memory you might have more luck with allocating dynamic memory for each line and storing the lines in a list. (you might be able to get a bunch of smaller chunks of memory but not one big piece)
Without knowing the context we can't tell, but normally you would parse the file into data structs rather than just storing the whole file in memory.
In JDK 7 you can use Files.readAllBytes(Path).
Example:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
Path path = Paths.get("path/to/file");
byte[] myByteArray = Files.readAllBytes(path);
Don't try reading the complete file into memory. Instead open a stream and process the file line by line (is it's a text file) or in parts. How that has to be done depends on the problem you are trying to solve.
EDIT: You say you want to upload a file, so please check this question. You don't need to have the complete file in memory.

Categories

Resources