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.
Related
I am trying to save the themes. I have themes(images) in drwable folder. I am showing the list of images and on click of the same I want to save the selected drawable resource in sharedpreferences and get the same from sharedpreferences.
To do that I thought to convert the drawable resourse into an uri and convert uri to string.
I tried to convert the drawable to uri like below :
public static String getURLForResource (int resourceId,Context context) {
//use BuildConfig.APPLICATION_ID instead of R.class.getPackage().getName() if both are not same
/* return Uri
.parse("android.resource://"+ BuildConfig.APPLICATION_ID +
"/" +resourceId).toString();*/
Resources resources = context.getResources();
return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
+ resources.getResourcePackageName(resourceId) + '/'
+ resources.getResourceTypeName(resourceId) + '/'
+ resources.getResourceEntryName(resourceId)).toString();
}
and retriving this uri string from sharedprefences and trying to convert it to bitmap:
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap =
BitmapFactory.decodeFile(sharedPreferencesData.getStr(
"ThemeName"),
options);*/
/* Uri myUri = Uri.parse(sharedPreferencesData.getStr(
"ThemeName"));
*/
/* Uri uri = Uri.parse(sharedPreferencesData.getStr("ThemeName"));
ContentResolver res = getContentResolver();
InputStream in = null;
try {
in = res.openInputStream(uri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap artwork = BitmapFactory.decodeStream(in);*/
try {
Uri uri = Uri.parse(sharedPreferencesData.getStr("ThemeName"));
Bitmap bitmap =
MediaStore.Images.Media
.getBitmap(this.getContentResolver(), uri);
/*
InputStream stream =
getAssets().open(sharedPreferencesData.getStr(
"ThemeName"));
Drawable d = Drawable.createFromStream(stream, null);
URL url_value = new URL(sharedPreferencesData.getStr(
"ThemeName").trim());
Bitmap mIcon1 =
BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
*/
I tried multiple ways none is working. Either the bitmap is empty or I am getting the File not found exception and malformedException.
Please help with the same.
EDIT :
I get the follwing string from getURLForResource :
D/ImageUri: android.resource://com.dailyfaithapp.dailyfaith/drawable/theme0
I have created a class with themename,font etc... and i am setting values to the same like :
public void setThemes(){
Themes themes = new Themes();
themes.setId(1);
themes.setImage(Utils.getURLForResource(R.drawable.theme1,this));
themes.setFont("AlexBrush-Regular.ttf");
themesArrayList.add(themes);
themes = new Themes();
themes.setId(2);
themes.setImage(Utils.getURLForResource(R.drawable.theme2,this));
themes.setFont("SkinnyJeans.ttf");
themesArrayList.add(themes);
themes = new Themes();
themes.setId(3);
themes.setImage(Utils.getURLForResource(R.drawable.theme3,this));
themes.setFont("Roboto-Thin.ttf");
themesArrayList.add(themes);
themes = new Themes();
themes.setId(4);
themes.setImage(Utils.getURLForResource(R.drawable.theme4,this));
themes.setFont("Raleway-Light.ttf");
themesArrayList.add(themes);
}
you can uri to drawable
public static Drawable uriToDrawable(Uri uri) {
Drawable d = null;
try {
InputStream inputStream;
inputStream = G.context.getContentResolver().openInputStream(uri);
d = Drawable.createFromStream(inputStream, uri.toString());
} catch (FileNotFoundException e) {
d = G.context.getResources().getDrawable(R.drawable.ic_launcher_background);
}
return d;
}
OR do these:
save bitmap in app root and again read
private void saveBitmap(Bitmap bitmap){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/images
File directory = cw.getDir("images", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"bg.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {}
}
Read Bitmap
private Bitmap readBitmap(String path)
{
try {
File f=new File(path, "bg.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
return b;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
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 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;
}
I am trying to load a file from the assets folder, the file name i want to be based on the current value of an int i (ie if i = 2 then open 2.txt and 2.jpg). I have the following code that deals with the asset manager side of things, and is working:
//link the image and text boxes to the xml
Image = (ImageView)findViewById(R.id.image);
Text = (TextView)findViewById(R.id.text);
loadDataFromAsset();
}
//actually load the text file and image file
public void loadDataFromAsset() {
//load the asset files themselves
try {
InputStream is = getAssets().open("1.txt");
//check file size
int size = is.available();
//create a buffer to handle it
byte[] buffer = new byte[size];
//send the data to the buffer
is.read(buffer);
//close the stream down
is.close();
//set the text we recovered to the TextView
Text.setText(new String(buffer));
}
catch (IOException ex) {
return;
}
//image file next
try {
InputStream ims = getAssets().open("1.jpg");
//load the image as drawable
Drawable d = Drawable.createFromStream(ims, null);
//set the drawable image to the imageview
Image.setImageDrawable(d);
}
catch (IOException ex) {
return;
}
}
I am new to java and dont really know how to move forward from here, how can i make the 1.jpg and 1.txt actually work based on the value of the int?
Thanks;
Andy
try this:
//actually load the text file and image file
public void loadDataFromAsset(int val) {
//load the asset files themselves
try {
InputStream is = getAssets().open(val + ".txt");
//check file size
int size = is.available();
//create a buffer to handle it
byte[] buffer = new byte[size];
//send the data to the buffer
is.read(buffer);
//close the stream down
is.close();
//set the text we recovered to the TextView
Text.setText(new String(buffer));
}
catch (IOException ex) {
return;
}
//image file next
try {
InputStream ims = getAssets().open(val + ".jpg");
//load the image as drawable
Drawable d = Drawable.createFromStream(ims, null);
//set the drawable image to the imageview
Image.setImageDrawable(d);
}
catch (IOException ex) {
return;
}
}
Try to use this for text
InputStream is = getResources().getAssets().open("yourINTvalue.txt");
String textfile = convertStreamToString(is);
Text.setText(textfile);
public static String convertStreamToString(InputStream is)
throws IOException {
Writer writer = new StringWriter();
char[] buffer = new char[2048];
try {
Reader reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
String text = writer.toString();
return text;
}
for image try this
InputStream bitmap=null;
try {
bitmap=getAssets().open("yourINTvalue.png");
Bitmap bit=BitmapFactory.decodeStream(bitmap);
img.setImageBitmap(bit);
} catch (IOException e) {
e.printStackTrace();
} finally {
bitmap.close();
}
try like this
InputStream is = getAssets().open(i+".txt");
actually i'm opening png files from assets folder with this code:
public static Bitmap loadImage( String imageName ){
if( imageName.charAt(0) == '/' ) {
imageName = imageName.substring(1);
}
imageName = imageName + ".png";
Bitmap image = BitmapFactory.decodeStream(getResourceAsStream(imageName));
return image;
}
public static InputStream getResourceAsStream( String resourceName ) {
if( resourceName.charAt(0) == '/' ) {
resourceName = resourceName.substring(1);
}
InputStream is = null;
try {
is = context.getAssets().open( resourceName );
} catch (IOException e) {e.printStackTrace();}
return is;
}
This code opens the bitmaps with full cuality and it takes a lot of time to open it. I will try to use RGB_565 to speed up the opening of the bitmap.
What should i change into my code to open the bitmap with RGB_565? As you can see, i dont know the width and the height of the image.
Also any sugerences to speed up the opening of the bitmap will be welcome
Thanks
Add BitmapFactory.Options to to decodeStream() call:
BitmapFactory.Options bitmapLoadingOptions = new BitmapFactory.Options();
bitmapLoadingOptions.inPreferredConfig = Bitmap.Config.RGB_565;
BitmapFactory.decodeStream(instream,null,bitmapLoadingOptions);
As for how to speed up loading the image? Not sure what else you can do except maybe reduce the size of the image if that's possible.
This code worked for me
AssetManager assetManager = getAssets();
InputStream istr = null;
try {
istr = assetManager.open(strName);
} catch (IOException e) {
e.printStackTrace();
}
BitmapFactory.Options bitmapLoadingOptions = new BitmapFactory.Options();
bitmapLoadingOptions.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap = BitmapFactory.decodeStream(istr,null,bitmapLoadingOptions);
return bitmap;