How can i make a screen shot programmatically and save it to sdcard, i tried this:
View v = getWindow().getDecorView().getRootView();
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
Util.saveBitmap(b, "snapshot", "screen");
class Util {
public static final int SDK_VERSION = getSdkVersion();
private static int getSdkVersion() {
try {
return Integer.parseInt(Build.VERSION.SDK);
} catch (NumberFormatException e) {
return 3;
}
}
static String saveBitmap(Bitmap bitmap, String dir, String baseName) {
try {
File sdcard = Environment.getExternalStorageDirectory();
File pictureDir = new File(sdcard, dir);
pictureDir.mkdirs();
File f = null;
for (int i = 1; i < 200; ++i) {
String name = baseName + i + ".png";
f = new File(pictureDir, name);
if (!f.exists()) {
break;
}
}
if (!f.exists()) {
String name = f.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(name);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
return name;
}
} catch (Exception e) {
} finally {
/*
if (fos != null) {
fos.close();
}
*/
}
return null;
}
static void bitmapBGRtoRGB(Bitmap bitmap, int width, int height) {
int size = width * height;
short data[] = new short[size];
ShortBuffer buf = ShortBuffer.wrap(data);
bitmap.copyPixelsToBuffer(buf);
for (int i = 0; i < size; ++i) {
//BGR-565 to RGB-565
short v = data[i];
data[i] = (short) (((v&0x1f) << 11) | (v&0x7e0) | ((v&0xf800) >> 11));
}
buf.rewind();
bitmap.copyPixelsFromBuffer(buf);
}
}
But it doesn't work
Related
I was using RecyclerView to create PDF previously. I want to add share and print functionality for which I want to create PDF with content in it. The method I was using was
public static void generatePDF(RecyclerView view, boolean isShareTrue, Context context, boolean isWeekly) {
RecyclerView.Adapter adapter = view.getAdapter();
Bitmap bigBitmap = null;
if (adapter != null) {
int size = adapter.getItemCount();
int height = 0;
Paint paint = new Paint();
int iHeight = 0;
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
LruCache<String, Bitmap> bitmaCache = new LruCache<>(cacheSize);
for (int i = 0; i < size; i++) {
RecyclerView.ViewHolder holder = adapter.createViewHolder(view, adapter.getItemViewType(i));
adapter.onBindViewHolder(holder, i);
holder.itemView.measure(View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(), holder.itemView.getMeasuredHeight());
holder.itemView.setDrawingCacheEnabled(true);
holder.itemView.buildDrawingCache();
Bitmap drawingCache = holder.itemView.getDrawingCache();
if (drawingCache != null) {
bitmaCache.put(String.valueOf(i), drawingCache);
}
height += holder.itemView.getMeasuredHeight();
}
bigBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), height, Bitmap.Config.ARGB_8888);
Canvas bigCanvas = new Canvas(bigBitmap);
bigCanvas.drawColor(Color.WHITE);
Document document = new Document(PageSize.A4);
File file;
if (isWeekly)
file = new File(Environment.getExternalStorageDirectory(), "Weekly_list_" + AppPreferences.INSTANCE.getUserId() + ".pdf");
else
file = new File(Environment.getExternalStorageDirectory(), "Open_Cycle_List_" + AppPreferences.INSTANCE.getUserId() + ".pdf");
try {
PdfWriter.getInstance(document, new FileOutputStream(file));
} catch (DocumentException | FileNotFoundException e) {
e.printStackTrace();
}
for (int i = 0; i < size; i++) {
try {
//Adding the content to the document
Bitmap bmp = bitmaCache.get(String.valueOf(i));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
- document.rightMargin() - 0) / image.getWidth()) * 100; // 0 means you have no indentation. If you have any, change it.
image.scalePercent(scaler);
image.setAlignment(com.itextpdf.text.Image.ALIGN_CENTER | com.itextpdf.text.Image.ALIGN_TOP);
if (!document.isOpen()) {
document.open();
}
document.add(image);
} catch (Exception ex) {
Log.e("TAG-ORDER PRINT ERROR", ex.getMessage());
}
}
if (document.isOpen()) {
document.close();
}
if (isShareTrue) {
Intent intentShareFile = new Intent(Intent.ACTION_SEND);
if (file.exists()) {
Uri pdfUri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
pdfUri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
} else {
pdfUri = Uri.fromFile(file);
}
intentShareFile.setType("application/pdf");
intentShareFile.putExtra(Intent.EXTRA_STREAM, pdfUri);
intentShareFile.putExtra(Intent.EXTRA_SUBJECT, "Sharing File...");
intentShareFile.putExtra(Intent.EXTRA_TEXT, "Sharing File...");
context.startActivity(Intent.createChooser(intentShareFile, "Share File"));
}
} else {
Toast.makeText(context, "PDF Generated successfully", Toast.LENGTH_LONG).show();
}
}
}
Now I have replaced recycler view with ExpandableListView and my print and share functionality is not working.
I want to create PDF with ExpandableListView content.
I know this question already exists, but I'm not sure how to implement it in my case...
First I created an DataOutuputStream that will write in a file with .uedl extension:
private static DataOutputStream os;
public static final String BASE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myApp/logs/"
public static void startReceiveLogs() {
if (debugBaudRate > -1) {
mReadFlag = true;
String time = TimeUtils.getCurrentTime(TimeZone.getDefault());
try {
os = new DataOutputStream(new FileOutputStream(BASE_PATH + time + "_logs.uedl"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
mReceiveLogsThread = new Thread(new ReceiveLogsThread());
mReceiveLogsThread.start();
}
}
Here is the writing stuff:
public void run() {
byte[] rbuf = new byte[64];
while (mReadFlag) {
try {
int len = mSerial.readLog(rbuf, mSerialPortLog);
if (len > 0) {
os.write(rbuf, 0, len);
}
} catch (NullPointerException e1) {
e1.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Once this thread stops running, I'd like to compress that file at the same path.
You try this it will help for you
public boolean zipFileAtPath(String sourcePath, String toLocation) {
final int BUFFER = 2048;
File sourceFile = new File(sourcePath);
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(toLocation);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
if (sourceFile.isDirectory()) {
zipSubFolder(out, sourceFile, sourceFile.getParent().length());
} else {
byte data[] = new byte[BUFFER];
FileInputStream fi = new FileInputStream(sourcePath);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(getLastPathComponent(sourcePath));
entry.setTime(sourceFile.lastModified()); // to keep modification time after unzipping
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
}
out.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private void zipSubFolder(ZipOutputStream out, File folder,
int basePathLength) throws IOException {
final int BUFFER = 2048;
File[] fileList = folder.listFiles();
BufferedInputStream origin = null;
for (File file : fileList) {
if (file.isDirectory()) {
zipSubFolder(out, file, basePathLength);
} else {
byte data[] = new byte[BUFFER];
String unmodifiedFilePath = file.getPath();
String relativePath = unmodifiedFilePath
.substring(basePathLength);
FileInputStream fi = new FileInputStream(unmodifiedFilePath);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(relativePath);
entry.setTime(file.lastModified()); // to keep modification time after unzipping
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
}
}
public String getLastPathComponent(String filePath) {
String[] segments = filePath.split("/");
if (segments.length == 0)
return "";
String lastPathComponent = segments[segments.length - 1];
return lastPathComponent;
}
I want to render a pdf which in the raw folder with ParcelFileDescriptor tried too many methods from the other posts but none of them worked for me. Below is the code
I copied the code from the post you suggested and modified my code but still pdf is not opening even its showing no error.
public void render()
{
try
{
imgv = (ImageView) findViewById(R.id.img);
int w = imgv.getWidth();
int h = imgv.getHeight();
Bitmap bm = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_4444);
File fileBrochure = new File(Environment.getExternalStorageDirectory() + "/" + "abcd.pdf");
if (!fileBrochure.exists())
{
CopyAssetsbrochure();
}
/** PDF reader code */
File file = new File(Environment.getExternalStorageDirectory() + "/" + "abcd.pdf");
// File file = new File("android.resource://com.nyt.ilm.mytestpdfreader/raw/abcd.pdf");
PdfRenderer render = new PdfRenderer(ParcelFileDescriptor.open(file,ParcelFileDescriptor.MODE_READ_ONLY));
if (CurrentPage < 0)
{ CurrentPage =0;
}
else if (CurrentPage > render.getPageCount()){
CurrentPage = render.getPageCount() - 1;
}
Matrix m = imgv.getImageMatrix();
Rect rect = new Rect(0,0,w,h);
render.openPage(CurrentPage).render(bm,rect,m,PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
imgv.setImageMatrix(m);
imgv.setImageBitmap(bm);
imgv.invalidate();
}
catch (Exception e)
{
e.printStackTrace();
}
}
//method to write the PDFs file to sd card
private void CopyAssetsbrochure() {
AssetManager assetManager = getAssets();
String[] files = null;
try
{
files = assetManager.list("");
}
catch (IOException e)
{
Log.e("tag", e.getMessage());
}
for(int i=0; i<files.length; i++)
{
String fStr = files[i];
if(fStr.equalsIgnoreCase("abcd.pdf"))
{
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open(files[i]);
out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
break;
}
catch(Exception e)
{
Log.e("tag", e.getMessage());
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
I want to design an app that generates a QR code and gives the user the possibility to save the generated image to their internal storage only. I successfully generate the bitmap and save it as .PNG image, but when I try to open it from the gallery it appears broken or corrupt.
Below is the code to generate the bitmap and display it on an ImageView(qrCode):
bitmap = encodeAsBitmap(value);
qrCode.setImageBitmap(bitmap);
Bitmap encodeAsBitmap(String str) throws WriterException {
BitMatrix result;
try {
result = new MultiFormatWriter().encode(str,
BarcodeFormat.QR_CODE, WIDTH, WIDTH, null);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int w = result.getWidth();
int h = result.getHeight();
int[] pixels = new int[w * h];
for (int y = 0; y < h; y++) {
int offset = y * w;
for (int x = 0; x < w; x++) {
pixels[offset + x] = result.get(x, y) ? getResources().getColor(R.color.colorBlack) :
getResources().getColor(R.color.colorWhite);
}
}
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, 500, 0, 0, w, h);
return bitmap;
}
It works perfectly up to this level. The user can then click a button in order to save this image to their device's internal storage, thanks to the below method:
public void onClickSaveCode(View view) {
String title = getResources().getString(R.string.saved_image_title_prepend) + stringDate;
String format = getResources().getString(R.string.saved_image_format);
String directory = getResources().getString(R.string.saved_image_directory);
// Method call to save image
saveImageToInternalStorage(bitmap, directory, title, format);
}
public boolean saveImageToInternalStorage(Bitmap bitmap, String directory, String title, String format) {
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File imageDirectory = contextWrapper.getDir(directory, Context.MODE_WORLD_READABLE);
File path = new File(imageDirectory, title + format);
try {
FileOutputStream fos = new FileOutputStream(path);
// Use the compress method on the Bitmap object to write image to the OutputStream
bitmap.compress(Bitmap.CompressFormat.PNG, QUALITY, fos);
fos.close();
new SingleMediaScanner(this, path);
Toast.makeText(this, getString(R.string.save_success), Toast.LENGTH_LONG).show();
return true;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, getString(R.string.save_failure), Toast.LENGTH_LONG).show();
return false;
}
}
And finally below is the MediaScannerConnection class to scan for all images saved to the device and display them in the gallery:
public class SingleMediaScanner implements MediaScannerConnectionClient {
private MediaScannerConnection mSC;
private File file;
public SingleMediaScanner(Context context, File f) {
file = f;
mSC = new MediaScannerConnection(context, this);
mSC.connect();
}
#Override
public void onMediaScannerConnected() {
mSC.scanFile(file.getAbsolutePath(), null);
}
#Override
public void onScanCompleted(String path, Uri uri) {
mSC.disconnect();
}
}
The images are saved, yet they appear in the gallery as broken files.
Any help will be greatly appreciated.
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
string filePath = System.IO.Path.Combine(path, "compressed.png");
//Bitmap bmp = ((BitmapDrawable)imgV.Drawable).Bitmap;
Bitmap b = newBitmap;
FileStream ms = new FileStream(filePath, FileMode.Create);
//FileOutputStream fos = new FileOutputStream(filePath,true);
await b.CompressAsync(Bitmap.CompressFormat.Png, 100, ms);
ms.Close();
//ByteArrayOutputStream opstream = new ByteArrayOutputStream();
//b.Compress(Bitmap.CompressFormat.Png, 100, opstream);
//byte[] bytArray = opstream.ToByteArray();
Toast.MakeText(Application.Context, "Compressed : " , ToastLength.Short).Show();
imgCompress.SetImageBitmap(b);
I am new to android platform. I need to create a text file in android. Please let me know how to perform this task in android. I have written a code that is working fine in java but not in android. Please help me on this....the sample code that ihave written is :-
try
{
DataOutputStream dos = new DataOutputStream(new FileOutputStream("test.txt", true));
dos.writeBytes(dataLine);
dos.close();
}
catch (FileNotFoundException ex) {}
the above code snippet is working fine in java but not in android :(
Thanks,
Ashish
The Android Dev Guide explains it nicely:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
If you want the files you create to be visible to the outside world, use external storage. But as I said in the comment, make sure you're "being a good citizen". These files stick around even after the user uninstalls your app.
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
/**
* Static methods used for common file operations.
*
* #author Carl Hartung (carlhartung#gmail.com)
*/
public class FileUtils {
private final static String t = "FileUtils";
// Used to validate and display valid form names.
public static final String VALID_FILENAME = "[ _\\-A-Za-z0-9]*.x[ht]*ml";
// Storage paths
public static final String FORMS_PATH = Environment.getExternalStorageDirectory() + "/odk/forms/";
public static final String INSTANCES_PATH = Environment.getExternalStorageDirectory() + "/odk/instances/";
public static final String CACHE_PATH = Environment.getExternalStorageDirectory() + "/odk/.cache/";
public static final String TMPFILE_PATH = CACHE_PATH + "tmp.jpg";
public static ArrayList<String> getValidFormsAsArrayList(String path) {
ArrayList<String> formPaths = new ArrayList<String>();
File dir = new File(path);
if (!storageReady()) {
return null;
}
if (!dir.exists()) {
if (!createFolder(path)) {
return null;
}
}
File[] dirs = dir.listFiles();
for (int i = 0; i < dirs.length; i++) {
// skip all the directories
if (dirs[i].isDirectory())
continue;
String formName = dirs[i].getName();
formPaths.add(dirs[i].getAbsolutePath());
}
return formPaths;
}
public static ArrayList<String> getFoldersAsArrayList(String path) {
ArrayList<String> mFolderList = new ArrayList<String>();
File root = new File(path);
if (!storageReady()) {
return null;
}
if (!root.exists()) {
if (!createFolder(path)) {
return null;
}
}
if (root.isDirectory()) {
File[] children = root.listFiles();
for (File child : children) {
boolean directory = child.isDirectory();
if (directory) {
mFolderList.add(child.getAbsolutePath());
}
}
}
return mFolderList;
}
public static boolean deleteFolder(String path) {
// not recursive
if (path != null && storageReady()) {
File dir = new File(path);
if (dir.exists() && dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
if (!file.delete()) {
Log.i(t, "Failed to delete " + file);
}
}
}
return dir.delete();
} else {
return false;
}
}
public static boolean createFolder(String path) {
if (storageReady()) {
boolean made = true;
File dir = new File(path);
if (!dir.exists()) {
made = dir.mkdirs();
}
return made;
} else {
return false;
}
}
public static boolean deleteFile(String path) {
if (storageReady()) {
File f = new File(path);
return f.delete();
} else {
return false;
}
}
public static byte[] getFileAsBytes(File file) {
byte[] bytes = null;
InputStream is = null;
try {
is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
Log.e(t, "File " + file.getName() + "is too large");
return null;
}
// Create the byte array to hold the data
bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int read = 0;
try {
while (offset < bytes.length && read >= 0) {
read = is.read(bytes, offset, bytes.length - offset);
offset += read;
}
} catch (IOException e) {
Log.e(t, "Cannot read " + file.getName());
e.printStackTrace();
return null;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
try {
throw new IOException("Could not completely read file " + file.getName());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return bytes;
} catch (FileNotFoundException e) {
Log.e(t, "Cannot find " + file.getName());
e.printStackTrace();
return null;
} finally {
// Close the input stream
try {
is.close();
} catch (IOException e) {
Log.e(t, "Cannot close input stream for " + file.getName());
e.printStackTrace();
return null;
}
}
}
public static boolean storageReady() {
String cardstatus = Environment.getExternalStorageState();
if (cardstatus.equals(Environment.MEDIA_REMOVED)
|| cardstatus.equals(Environment.MEDIA_UNMOUNTABLE)
|| cardstatus.equals(Environment.MEDIA_UNMOUNTED)
|| cardstatus.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
return false;
} else {
return true;
}
}
public static String getMd5Hash(File file) {
try {
// CTS (6/15/2010) : stream file through digest instead of handing it the byte[]
MessageDigest md = MessageDigest.getInstance("MD5");
int chunkSize = 256;
byte[] chunk = new byte[chunkSize];
// Get the size of the file
long lLength = file.length();
if (lLength > Integer.MAX_VALUE) {
Log.e(t, "File " + file.getName() + "is too large");
return null;
}
int length = (int) lLength;
InputStream is = null;
is = new FileInputStream(file);
int l = 0;
for (l = 0; l + chunkSize < length; l += chunkSize) {
is.read(chunk, 0, chunkSize);
md.update(chunk, 0, chunkSize);
}
int remaining = length - l;
if (remaining > 0) {
is.read(chunk, 0, remaining);
md.update(chunk, 0, remaining);
}
byte[] messageDigest = md.digest();
BigInteger number = new BigInteger(1, messageDigest);
String md5 = number.toString(16);
while (md5.length() < 32)
md5 = "0" + md5;
is.close();
return md5;
} catch (NoSuchAlgorithmException e) {
Log.e("MD5", e.getMessage());
return null;
} catch (FileNotFoundException e) {
Log.e("No Cache File", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Problem reading from file", e.getMessage());
return null;
}
}
}
Try this
final File sdcard=Environment.getExternalStorageDirectory();
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
File path=new File(sdcard,"textfile.txt");
try {
BufferedWriter wr=new BufferedWriter(new FileWriter(path));
wr.write("Your Text Here");
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Also you need to add following permission to your manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>