How to share image Generated Bitmap [duplicate] - java

This question already has answers here:
Sharing Bitmap via Android Intent
(9 answers)
Closed 3 years ago.
People would like to know how I share an image generated within the app,
in the app's scope the person writing in the text view it captures and generates an image would like to share that image via whats or email.
private void gerarQRCode() {
String texto = edtTexto.getText().toString();
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
BitMatrix bitmatrix = multiFormatWriter.encode(texto, BarcodeFormat.QR_CODE, 2000, 2000);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitmatrix);
ivQRCode.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}

Step #1: Write the Bitmap to a file on internal storage, using the compress() method
Step #2: Set up FileProvider to be able to serve files from where you are storing the bitmap
Step #3: Use FileProvider.getUriForFile() to get a Uri representing that bitmap
Step #4: Use ACTION_SEND to offer that bitmap to other apps for sharing purposes

Related

Is it possible to reduce quality of video file before uploading via android?

I am currently trying to reduce the quality of videos and audio before uploading to and online cloud database. Below is the code I have been using to record videos.
recordVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
Changing the 0 to 1 in EXTRA_VIDEO_QUALITY will increase the quality and vice versa, but the file is still too large to download if it a 30 second or more video.
private void RecordVideoMode() {
Intent recordVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (recordVideoIntent.resolveActivity(getPackageManager()) != null) {
videoFile = createVideoFile();
// Continue only if the File was successfully created
if (videoFile != null) {
videoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
videoFile);
recordVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
recordVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, videoURI);
startActivityForResult(recordVideoIntent, REQUEST_VIDEO_CAPTURE);
}
}
}
Any help is very much appreciated!
You can go with this two methods :
Encode it to a lower bit rate and/or lower resolution. Have a look here:
Is it possible to compress video on Android?
Try to zip/compress it. Have a look here:
http://www.jondev.net/articles/Zipping_Files_with_Android_%28Programmatically%29

ImageView doesn't display JPEG

I have an ImageView that is not wanting to display a JPEG, but will display all the other PNG's in the ListView. I have tried things such as adding a transparent background, and nothing works. To get the data, I downloaded all of the images, and stored them into a blob in a SQLite database. I retrieved them by fetching the info from the database, and according to the database, their is binary JPEG data available.
Here is the image I am trying to display (I have it already downloaded in binary data): http://image-store.slidesharecdn.com/1a4f1444-02e2-11e4-9166-22000a901256-large.jpeg
Here is the code I am using to try and convert the binary data back to a Bitmap:
try
{
String profilePictureBytes = submittedImageTemp; // this string holds the binary jpeg, png data, etc.
byte[] encoded;
try
{
encoded = profilePictureBytes.getBytes("ISO-8859-1");
ByteArrayInputStream imageStream = new ByteArrayInputStream(encoded);
Bitmap theBitmap = BitmapFactory.decodeStream(imageStream);
attachPreviewOne.setBackgroundColor(Color.TRANSPARENT);
attachPreviewOne.setImageBitmap(theBitmap);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
A. Extract your jpeg from the blob to a temp file. You might want to use the getCacheDir() folder for that
B. Load it from temp file:
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bm = BitmapFactory.decodeFile(jpegTemFile, options); //<------------
imageView.setImageBitmap(bm);
The above should work fine. Still - few things you might want to consider:
C. Depending on your jpeg, the loading operation - decodeFile - might be lengthy. You might want to do it in an
AsyncTask.
D. You might also want to consider setting a sampleSize so to reduce size of loaded image:
options.inSampleSize = 2; // setting to N will reduce in-memory size by factor of N*N
Or, you might use Picasso for the job. I used it in several projects and was happy with what I got:
Picasso.with(context)
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView)

Dynamic naming of Resources in Android without getIdentifier

I'm using OpenGL ES to make a game in Android. I got some code from a tutorial and I'm trying to change it to suit my app but I'm having a problem. I want to dynamically get an image resource using a string passed into a function as the resource name. I know usually you use getIdentifier() in this case, but that returns an int and I need an input stream. Is there any way of getting an input stream from a resource dynamically?
Alternatively, is there a better way of doing this?
Code below:
InputStream is = mContext.getResources().openRawResource(R.drawable.<imagename>);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is);
}
finally {
try {
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
yes u can Suppose u have images stored in drawable with naming img1,img2,img3,img4,img5,img6,img7 than
first make an array like
String[] imgarray={"img1","img2","img3","img4","img5","img6","img7"};
public static String PACKAGE_NAME ;
PACKAGE_NAME=getApplicationContext().getPackageName();
Random r = new Random();
int n=r.nextInt(imgarray.length());
int resID = getResources().getIdentifier( PACKAGE_NAME+":drawable/" +imgarray[n] , null, null);
imageview.setImageResource(resID);
if want bitmap image than just add below line
Bitmap bm = BitmapFactory.decodeResource(getResources(),resID);
if u want other way with less coding than see accepted answer at Other Example

java.lang.OutOfMemoryError: bitmap size exceeds VM budget [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android: Strange out of memory issue while loading an image to a Bitmap object
I am getting following error when I load bitmap on imageview in AsyncTask:
Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget
Is there any help?
It could be helpful to watch the memory management session of this year's google i/o:
Memory management for Android Apps Here, Patrick Dubroy explains some cases which can lead to memory leaks (particularly keeping a long lived reference to the application's context via static members). He also talks about the garbage collector.
I had the same problem.
I solved the problem resampling the bitmap to lower resolution, and then using imageView.clearAnimation(); before to load the new bitmap on the imageView.
Vote me if this helps you too.
Regards.
Note: in the following sample, data contains the new image data for the camera image picker and imageView is our ImageView.
Bitmap photo=null;
imageView.clearAnimation();
Uri photoUri = data.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(photoUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
options.inSampleSize=2;
Rect outPadding= new Rect(-1, -1, -1, -1);
photo = BitmapFactory.decodeStream(imageStream, outPadding, options);
imageView.setImageBitmap(photo);

BitmapFactory.decodeResource returns a mutable Bitmap in Android 2.2 and an immutable Bitmap in Android 1.6

I am developing an application and testing it on my device running Android 2.2. In my code, I make use of a Bitmap that I retrieve using BitmapFactory.decodeResource, and I am able to make changes by calling bitmap.setPixels() on it. When I test this on a friend's device running Android 1.6, I get an IllegalStateException in the call to bitmap.setPixels. Documentation online says an IllegalStateException is thrown from this method when the bitmap is immutable. The documentation doesn't say anything about decodeResource returning an immutable bitmap, but clearly that must be the case.
Is there a different call I can make to get a mutable bitmap reliably from an application resource without needing a second Bitmap object (I could create a mutable one the same size and draw into a Canvas wrapping it, but that would require two bitmaps of equal size using up twice as much memory as I had intended)?
You can convert your immutable bitmap to a mutable bitmap.
I found an acceptable solution that uses only the memory of one bitmap.
A source bitmap is raw saved (RandomAccessFile) on disk (no ram memory), then source bitmap is released, (now, there's no bitmap at memory), and after that, the file info is loaded to another bitmap. This way is possible to make a bitmap copy having just one bitmap stored in ram memory per time.
See the full solution and implementation here: Android: convert Immutable Bitmap into Mutable
I add a improvement to this solution, that now works with any type of Bitmaps (ARGB_8888, RGB_565, etc), and deletes the temp file. See my method:
/**
* Converts a immutable bitmap to a mutable bitmap. This operation doesn't allocates
* more memory that there is already allocated.
*
* #param imgIn - Source image. It will be released, and should not be used more
* #return a copy of imgIn, but muttable.
*/
public static Bitmap convertToMutable(Bitmap imgIn) {
try {
//this is the file going to use temporally to save the bytes.
// This file will not be a image, it will store the raw image data.
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "temp.tmp");
//Open an RandomAccessFile
//Make sure you have added uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
//into AndroidManifest.xml file
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
// get the width and height of the source bitmap.
int width = imgIn.getWidth();
int height = imgIn.getHeight();
Config type = imgIn.getConfig();
//Copy the byte to the file
//Assume source bitmap loaded using options.inPreferredConfig = Config.ARGB_8888;
FileChannel channel = randomAccessFile.getChannel();
MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, imgIn.getRowBytes()*height);
imgIn.copyPixelsToBuffer(map);
//recycle the source bitmap, this will be no longer used.
imgIn.recycle();
System.gc();// try to force the bytes from the imgIn to be released
//Create a new bitmap to load the bitmap again. Probably the memory will be available.
imgIn = Bitmap.createBitmap(width, height, type);
map.position(0);
//load it back from temporary
imgIn.copyPixelsFromBuffer(map);
//close the temporary file and channel , then delete that also
channel.close();
randomAccessFile.close();
// delete the temp file
file.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return imgIn;
}
Copy the bitmap to itself with mutable option true. This way neither extra memory consumption nor long lines of code are needed.
Bitmap bitmap= BitmapFactory.decodeResource(....);
bitmap= bitmap.copy(Bitmap.Config.ARGB_8888, true);
We can first set options for BitmapFactory by instantiating an BitmapFactory.Options class and then set the options field named 'inMutable' as true and and then pass this options instance to decodeResource.
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inMutable = true;
Bitmap bp = BitmapFactory.decodeResource(getResources(), R.raw.white, opt);
Here's a solution i've created that uses the internal storage and doesn't require any new permission, based on "Derzu"'s idea, and the fact that starting with honeycomb, this is built in :
/**decodes a bitmap from a resource id. returns a mutable bitmap no matter what is the API level.<br/>
might use the internal storage in some cases, creating temporary file that will be deleted as soon as it isn't finished*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static Bitmap decodeMutableBitmapFromResourceId(final Context context, final int bitmapResId) {
final Options bitmapOptions = new Options();
if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB)
bitmapOptions.inMutable = true;
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), bitmapResId, bitmapOptions);
if (!bitmap.isMutable())
bitmap = convertToMutable(context, bitmap);
return bitmap;
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static Bitmap convertToMutable(final Context context, final Bitmap imgIn) {
final int width = imgIn.getWidth(), height = imgIn.getHeight();
final Config type = imgIn.getConfig();
File outputFile = null;
final File outputDir = context.getCacheDir();
try {
outputFile = File.createTempFile(Long.toString(System.currentTimeMillis()), null, outputDir);
outputFile.deleteOnExit();
final RandomAccessFile randomAccessFile = new RandomAccessFile(outputFile, "rw");
final FileChannel channel = randomAccessFile.getChannel();
final MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, imgIn.getRowBytes() * height);
imgIn.copyPixelsToBuffer(map);
imgIn.recycle();
final Bitmap result = Bitmap.createBitmap(width, height, type);
map.position(0);
result.copyPixelsFromBuffer(map);
channel.close();
randomAccessFile.close();
outputFile.delete();
return result;
} catch (final Exception e) {
} finally {
if (outputFile != null)
outputFile.delete();
}
return null;
}
another alternative is to use JNI in order to put the data into it, recycle the original bitmap, and use the JNI data to create a new bitmap, which will be (automatically) mutable, so together with my JNI solution for bitmaps, one can do the following:
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
final JniBitmapHolder bitmapHolder=new JniBitmapHolder(bitmap);
bitmap.recycle();
bitmap=bitmapHolder.getBitmapAndFree();
Log.d("DEBUG",""+bitmap.isMutable()); //will return true
however, i'm not sure what is the minimal requirement of API level. it works very well on API 8 and above.
I know I'm late to the party, but this is how we avoided this painfully annoying Android problem, and cropped and modified an image with only one copy ever in memory.
Situation
we want to process the pixels of a cropped version of an image saved to file. With high memory demands, we never want to have more than one copy of this image in memory at any given time.
What should have worked but didn't
Opening the image subsection (the bit we wanted to crop to) with BitmapRegionDecoder, passing in a BitmapFactory.option with inMutable = true, processing the pixels then saving to file.
Though our app declared an API minimum of 14 and a target of 19, BitmapRegionDecoder was returning an immutable bitmap, effectively ignoring our BitMapFactory.options
What won't work
opening an mutable image with BitmapFactory (which respects our inMutable option) and croppping it: all cropping techniques are non-imperitive (require a copy of the entire image to exist in memory at a time, even if garbage collected immediately after with overwrites and recycling)
opening an immutable image with BitmapRegionDecoder (effectively cropped) and converting it to a mutable one; all available techniques again require a copy in memory.
The great work-around of 2014
open the full size image with BitmapFactory as a mutable bitmap, and perform our pixel operations
save the bitmap to file and recycle it from memory (it's still un-cropped)
open the saved bitmap with BitmapRegionDecoder, opening only the region to be cropped to (now we don't care if the bitmap is immutable or not)
save this bitmap (which has effectively been cropped) to file, overwriting the previously saved bitmap (which was un-cropped)
With this method, we can crop and perform pixel processing on a bitmap with only 1 copy ever in memory (so we can avoid those pesky OOM errors as much as possible), trading RAM for time as we have to perform extra (slow) file IOs.
It is happening because you want to resize the bitmap by calling setHeight() or setWidth()
To resize any bitmap or drawable (Png, Svg, vector, etc)
public Bitmap editMyBitmap(int drawableId, int newHeight, int newWidth) {
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), drawableId);
myBitmap = Bitmap.createScaledBitmap(myBitmap, newWidth, newHeight, false);
return myBitmap;
}
Usage Example:
Bitmap facebookIcon = editMyBitmap(R.drawable.facebookImage);
// now use it anywhere
imageView.setBitmapImage(facebookIcon);
canvas.drawBitmap(facebookIcon, 0, 0, null);
I know the question is solved but what about:
BitmapFactory.decodeStream(getResources().openRawResource(getResources().getIdentifier("bitmapname", "drawable", context.getPackageName())))

Categories

Resources