I am trying to get screenshot of the view as follows. I am getting Bitmap and I need to convert it to to Image to add into PDF generator.
using (var screenshot = Bitmap.CreateBitmap(200, 100,Bitmap.Config.Argb8888))
{
var canvas = new Canvas(screenshot);
rootView.Draw(canvas);
using (var screenshotOutputStream = new FileStream(screenshotPath,System.IO.FileMode.Create))
{
screenshot.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 90, screenshotOutputStream);
screenshotOutputStream.Flush();
screenshotOutputStream.Close();
}
}
My question is how to convert Android.Graphics.Bitmap -->screenshot to Image ?
I want to replace the url with Image itself which comes from BitMap.
String imageUrl = "myURL";
Image image = Image.GetInstance (new Uri (imageUrl));
document.Add(image);
You can use this method:
public Bitmap getScreenshotBmp() {
FileOutputStream fileOutputStream = null;
File path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String uniqueID = UUID.randomUUID().toString();
File file = new File(path, uniqueID + ".jpg");
try {
fileOutputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
screenshot.compress(Bitmap.CompressFormat.JPEG, 30, fileOutputStream);
try {
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return screenshot;
}
Related
So, I am creating a QRCode generator application in which user can generate QR code from the data they have entered.I can successfully generate the QR code and show it to the imageview on a Button click but I am facing issue when I tried to save that QR code to my phone's storage (or gallery).
On this button click, QRGenerator function will be called and It will generate the QR code from the Edittext data.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
QRGenerator();
}
});
Here is the QRGenerator() funcion :
private void QRGenerator() {
String data = text.getText().toString();
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
BitMatrix bitMatrix = multiFormatWriter.encode(data, BarcodeFormat.QR_CODE, 300, 300);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
imgView.setImageBitmap(bitmap);
bitmap2 = ((BitmapDrawable)imgView.getDrawable()).getBitmap();
saveImg.setVisibility(View.VISIBLE);
} catch (WriterException e) {
e.printStackTrace();
}
}
and from here I can call the save image function :
saveImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveImageFunction(bitmap2);
}
});
and here my issue arise, I have put a Toast to notify when my image will saved to gallery but it never pops up
Here is the saveImageFunction :
private void saveImageFunction(Bitmap bitmap) {
String savedImagePath = null;
String imageFileName = "JPEG_" + "test" + ".jpg";
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+ "/Demo");
boolean success = true;
if(!storageDir.exists()){
success = storageDir.mkdirs();
}
if(success){
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
addToGallery(savedImagePath);
Toast.makeText(MainActivity.this,"Saved to Gallery!",Toast.LENGTH_SHORT).show();
}
}
and to put that saved image to gallery I have used this function :
addToGallery() :
private void addToGallery(String imagePath){
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(imagePath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
As per Gk Mohammad Emon says, I tried adding Toast as well as Log.d in my catch method of SaveImage function but nothing pops up neither on Screen nor in LogCat (Please address any type of mistake if there) :
private void saveImageFunction(Bitmap bitmap) {
String savedImagePath = null;
String imageFileName = "JPEG_" + "test" + ".jpg";
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+ "/Demo");
boolean success = true;
if(!storageDir.exists()){
success = storageDir.mkdirs();
}
if(success){
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
Toast.makeText(MainActivity.this,"Image Saved!", Toast.LENGTH_SHORT).show();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,"hello There",Toast.LENGTH_SHORT).show();
Log.d("Exception e",e.toString());
}
addToGallery(savedImagePath);
Toast.makeText(MainActivity.this,"Saved to Gallery!",Toast.LENGTH_SHORT).show();
}
}
i need to load a image from assets to avoid a froyo 2.2.2 bug resizing POT images in some particular cases. The way to avoid it is loading the image files from assets dir.
I'm trying to do with this:
String imagePath = "radiocd5.png";
AssetManager mngr = context.getAssets();
// Create an input stream to read from the asset folder
InputStream is = null;
try {
is = mngr.open(imagePath);
} catch (IOException e1) { e1.printStackTrace();}
//Get the texture from the Android resource directory
//InputStream is = context.getResources().openRawResource(R.drawable.radiocd5);
Bitmap bitmap = null;
try {
//BitmapFactory is an Android graphics utility for images
bitmap = BitmapFactory.decodeStream(is);
} finally {
//Always clear and close
try {
is.close();
is = null;
} catch (IOException e) {}
}
But i am getting NullPointerException on the line is.close();
i capture a FileNotFoundException: radiocd5.png, but that file is on my assets directory :S
What am i doing bad? The file is called radiocd5.png and it is on the assets directory
You can follow my tutorials on displaying data from Assets: https://xjaphx.wordpress.com/2011/10/02/store-and-use-files-in-assets/
The sample with loading image and text to display.
I now added the relevant part of the provided link
(in case of earthquake or something) ;-) Taifun
// load image
try {
// get input stream
InputStream ims = getAssets().open("avatar.jpg");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
mImage.setImageDrawable(d);
}
catch(IOException ex) {
return;
}
Instead of using the assets dir, put the file into /res/raw, and you can then access it using the following URI: android.resource://com.your.packagename/" + R.raw.radiocd5
try {
InputStream istr = this.context.getAssets().open(P.strImage);
//set drawable from stream
this.imgProduct.setImageDrawable(Drawable.createFromStream(istr, null));
} catch (IOException e) {
e.printStackTrace();
}
protected String openImageInAssets(String imageName) {
String encodedImageBase64 = "";
AssetManager assetManager = getAssets();
InputStream fileStream = null;
try {
fileStream = assetManager.open(imageName);
if (fileStream != null) {
// BitmapFactory.Options bfo = new BitmapFactory.Options();
// bfo.inPreferredConfig = Bitmap.Config.ARGB_8888;
// Bitmap bitmap = BitmapFactory.decodeStream(fileStream, null, bfo);
Bitmap bitmap = BitmapFactory.decodeStream(fileStream);
// Convert bitmap to Base64 encoded image for web
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// to get image extension file name split the received
int fileExtensionPosition = imageName.lastIndexOf('.');
String fileExtension = imageName.substring(fileExtensionPosition+1);
// Log.d(IConstants.TAG,"fileExtension: " + fileExtension);
if (fileExtension.equalsIgnoreCase("png")) {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
// Log.d(IConstants.TAG,"fileExtension is PNG");
} else if (fileExtension.equalsIgnoreCase("jpg") || fileExtension.equalsIgnoreCase("jpeg")) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
// Log.d(TAG,"fileExtension is JPG");
}
byte[] byteArray = byteArrayOutputStream.toByteArray();
String imgageBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
encodedImageBase64 = "data:image/png;base64," + imgageBase64;
}
} catch (IOException e) {
e.printStackTrace();
return encodedImageBase64="";
} finally {
//Always clear and close
try {
if (fileStream != null) {
fileStream.close();
fileStream = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Log.d(TAG,"encodedImageBase64: " + encodedImageBase64);
return encodedImageBase64;
}
Here is an alternative way
setImageBitmap(BitmapFactory.decodeStream(assets.open("photo.jpg")))
Another version, inside a fragment:
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.createrestaurant_layout, container, false);
Resources res = getResources();
img = (ImageView) root.findViewById(R.id.img);
AssetManager amanager = res.getAssets();
try {
InputStream imageStream = amanager.open("restaurant.jpg");
Drawable drawable = new BitmapDrawable(res, imageStream);
img.setImageDrawable(drawable);
} catch (Exception e) {
e.printStackTrace();
}
}
This process seems much simpler in iOS/UIKit or iOS/SwiftUI.
Having trouble with File coding. This code basically save the bitmap file into android gallery.
Java.IO.File MyDirectory = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures), "MyDirectory");
Java.IO.File MyFile= new Java.IO.File(MyDirectory , String.Format("Photo{0}.jpg", Guid.NewGuid()));
Bitmap photo;
Bundle extras = data.Extras;
photo = (Bitmap)extras.Get("data")
How to save the photo (Bitmap) into MyFolder android gallery?
I have tried this to save the photo:
Java.IO.FileOutputStream outFile = new Java.IO.FileOutputStream(MyFile);
photo.Compress(Bitmap.CompressFormat.Png, 100, outFile);
Error I received is when the photo is compress..
error: Cannot convert from Java.IO.FileOutputStream to System.IO.Stream.
Sorry, I am very newbie in File coding. Any helps or solutions are appreciated.
Here is my code.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
public static void saveBitmap(Context context, Bitmap bitmap) {
String env = Environment.getExternalStorageDirectory().getPath();
String path = env + "/test.png";
try {
File f = new File(path);
FileOutputStream fileOut = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOut);
try {
fileOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bitmap.recycle();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This should work
var file = new FileStream(fname, FileMode.Create, FileAccess.Write, FileShare.None);
photo.Compress(Bitmap.CompressFormat.Jpeg, 85, file);
I use alternative way to compress my bitmap (using MemoryStream) and here is my code.
using(Bitmap bitmap = BitmapFactory.DecodeFile(myFileString))
{
MemoryStream stream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
myWebService.functionSave(stream.ToArray());
}
//myWebservice function parameter.
functionSave(byte[] fileStream)
{
//... save your bitmap code using byte[]
}
i need to load a image from assets to avoid a froyo 2.2.2 bug resizing POT images in some particular cases. The way to avoid it is loading the image files from assets dir.
I'm trying to do with this:
String imagePath = "radiocd5.png";
AssetManager mngr = context.getAssets();
// Create an input stream to read from the asset folder
InputStream is = null;
try {
is = mngr.open(imagePath);
} catch (IOException e1) { e1.printStackTrace();}
//Get the texture from the Android resource directory
//InputStream is = context.getResources().openRawResource(R.drawable.radiocd5);
Bitmap bitmap = null;
try {
//BitmapFactory is an Android graphics utility for images
bitmap = BitmapFactory.decodeStream(is);
} finally {
//Always clear and close
try {
is.close();
is = null;
} catch (IOException e) {}
}
But i am getting NullPointerException on the line is.close();
i capture a FileNotFoundException: radiocd5.png, but that file is on my assets directory :S
What am i doing bad? The file is called radiocd5.png and it is on the assets directory
You can follow my tutorials on displaying data from Assets: https://xjaphx.wordpress.com/2011/10/02/store-and-use-files-in-assets/
The sample with loading image and text to display.
I now added the relevant part of the provided link
(in case of earthquake or something) ;-) Taifun
// load image
try {
// get input stream
InputStream ims = getAssets().open("avatar.jpg");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
mImage.setImageDrawable(d);
}
catch(IOException ex) {
return;
}
Instead of using the assets dir, put the file into /res/raw, and you can then access it using the following URI: android.resource://com.your.packagename/" + R.raw.radiocd5
try {
InputStream istr = this.context.getAssets().open(P.strImage);
//set drawable from stream
this.imgProduct.setImageDrawable(Drawable.createFromStream(istr, null));
} catch (IOException e) {
e.printStackTrace();
}
protected String openImageInAssets(String imageName) {
String encodedImageBase64 = "";
AssetManager assetManager = getAssets();
InputStream fileStream = null;
try {
fileStream = assetManager.open(imageName);
if (fileStream != null) {
// BitmapFactory.Options bfo = new BitmapFactory.Options();
// bfo.inPreferredConfig = Bitmap.Config.ARGB_8888;
// Bitmap bitmap = BitmapFactory.decodeStream(fileStream, null, bfo);
Bitmap bitmap = BitmapFactory.decodeStream(fileStream);
// Convert bitmap to Base64 encoded image for web
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// to get image extension file name split the received
int fileExtensionPosition = imageName.lastIndexOf('.');
String fileExtension = imageName.substring(fileExtensionPosition+1);
// Log.d(IConstants.TAG,"fileExtension: " + fileExtension);
if (fileExtension.equalsIgnoreCase("png")) {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
// Log.d(IConstants.TAG,"fileExtension is PNG");
} else if (fileExtension.equalsIgnoreCase("jpg") || fileExtension.equalsIgnoreCase("jpeg")) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
// Log.d(TAG,"fileExtension is JPG");
}
byte[] byteArray = byteArrayOutputStream.toByteArray();
String imgageBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
encodedImageBase64 = "data:image/png;base64," + imgageBase64;
}
} catch (IOException e) {
e.printStackTrace();
return encodedImageBase64="";
} finally {
//Always clear and close
try {
if (fileStream != null) {
fileStream.close();
fileStream = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Log.d(TAG,"encodedImageBase64: " + encodedImageBase64);
return encodedImageBase64;
}
Here is an alternative way
setImageBitmap(BitmapFactory.decodeStream(assets.open("photo.jpg")))
Another version, inside a fragment:
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.createrestaurant_layout, container, false);
Resources res = getResources();
img = (ImageView) root.findViewById(R.id.img);
AssetManager amanager = res.getAssets();
try {
InputStream imageStream = amanager.open("restaurant.jpg");
Drawable drawable = new BitmapDrawable(res, imageStream);
img.setImageDrawable(drawable);
} catch (Exception e) {
e.printStackTrace();
}
}
This process seems much simpler in iOS/UIKit or iOS/SwiftUI.
i want to create a bitmap of whats being currently displayed of my app, one thing i went into is cant read FB buffer requires root, would like to know if it is possible to create a image file for the screen, please i want the help to code this, no 3rd party intents , thanks, answers would be much appreciated
From your Activity (pseudo-code):
Bitmap bm = Bitmap.create...
Canvas canvas = new Canvas(bm);
getWindow.getDecorView().draw(canvas);
You can use FFMPEG to capture the Screen
Try this.....
{
LinearLayout view = (LinearLayout) findViewById(R.id.imageLayout);
View v1 = view.getRootView();
v1.setDrawingCacheEnabled(true);
String dir="myimages";
Bitmap bm = v1.getDrawingCache();
saveBitmap(bm, dir, "capturedimage");
}
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;
}
}
System.out.println("Image size : "+bitmap.getHeight());
if (!f.exists()) {
String name = f.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(name);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
System.out.println("After File Size : "+f.length());
fos.flush();
fos.close();
return name;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception in saveBitmap: "+e.getMessage());
} finally {
}
return null;
}