Created
June 14, 2020 02:12
-
-
Save BetelGeuseee/c830d489e1a5fc511f4ff4d3adfb4672 to your computer and use it in GitHub Desktop.
Adding image from gallery and changing it into byte array and Bitmap(Vice versa)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//opening gallery and choosing image ,,,Here gallery request code final string of any number more than zero(3 digit) | |
Intent intent = new Intent(); | |
intent.setType("image/*"); //this is done because it allows to select any kind of image | |
intent.setAction(Intent.ACTION_GET_CONTENT); | |
startActivityForResult(Intent.createChooser(intent,"Pick Image"),GALLERY_REQUEST_CODE); | |
//this will be called every time you choose image from the gallery | |
@Override | |
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { | |
//checking request code ==gallery code or not? and checking we have valid image data or not | |
if (requestCode == GALLERY_REQUEST_CODE && resultCode == RESULT_OK && data != null) { | |
Uri imageData = data.getData(); //this is done to store image data in URI variable | |
profilepic.setImageURI(imageData); //changes the image URI to image data that user selected; | |
//******************************************************************************************************** | |
InputStream imageStream = null; | |
try { | |
imageStream = getContentResolver().openInputStream(imageData); | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); | |
} | |
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream); | |
convertImage(yourSelectedImage); | |
} | |
super.onActivityResult(requestCode, resultCode, data); | |
} | |
public void convertImage(Bitmap bitmap){ | |
ByteArrayOutputStream stream = new ByteArrayOutputStream(); | |
bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream); | |
array= stream.toByteArray(); | |
bitmap.recycle(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment