Make an Image as a backgound in java android for edit - java

I had created an image by the following code:
Bitmap bmp = Bitmap.createBitmap(512, 512, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
try {
int tile1ResID = getResources().getIdentifier("drawable/m" + String.valueOf(tileOfPoint.x) + "_" + String.valueOf(tileOfPoint.y), "drawable", "com.example.sabtt1");
canvas.drawBitmap(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), tile1ResID), 256, 256, true), 0, 0, null);
canvas.save();
}
catch (Exception e) {
}
canvas.save();
ImageView imgMap1 = (ImageView) findViewById(R.id.imgMap1);
imgMap1.setImageDrawable(new BitmapDrawable(Bitmap.createBitmap(bmp, 0, 0, 500, 500)));
now I want to make it as background. So that the user can add an image or draw on it.
How can I set it as background?
Is it possible to add the image and draw by finger at the same time?
I use this code for draw:
#Override
public void onClick(View arg0) {
try {
Bitmap gestureImg = gesture.getGesture().toBitmap(100, 100, 8, Color.BLACK);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
gestureImg.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] bArray = bos.toByteArray();
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra("draw", bArray);
startActivity(intent);
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(Activity1.this, "No draw on the string", 3000).show();
}
}
and OnDragListener for add and move images.
I know that I should use the folowing code for background:
LinearLayout ll = new LinearLayout(this);
ll.setBackgroundResource(R.drawable.nn);
this.setContentView(ll);
but by using this code, I can't see other images.
Thanks in advance.

You can just draw on the main bitmap the other bitmaps:
Bitmap bmp = Bitmap.createBitmap(512, 512, Bitmap.Config.ARGB_8888);
bmp = <load from resource>
Canvas canvas = new Canvas(bmp);
Bitmap gestureImg = <get bitmap from gesture or loading>
canvas.drawBitmap(gestureImg);
then load the final bitmap:
ImageView imgMap1 = (ImageView) findViewById(R.id.imgMap1);
imgMap1.setImageDrawable(new BitmapDrawable(Bitmap.createBitmap(bmp, 0, 0, 500, 500)));
Or you can store the main bitmap and all other gesture/loaded bitmaps in separate objects and when you want to update the imgMap1 you make your combined bitmap;
Also to use as background the new bitmap use:
ll.setBackgroundDrawable( new BitmapDrawable( bmp ) );

Related

Google maps snapshot getting removed from Canvas

I'm trying to create a screenshot of my Activity with a Google map in it. My code stopped working after updating my Google API's from 7.xx to 8.1.0`, but i can't find any relevant changes in their changelogs.
This is what happens: I take a screenshot of my activity with view.getDrawingCache. I then draw the snapshot of the map on the correct position on my canvas. This all works fine. When i want to draw my "backBitmap" over my snapshot, it removed the snapshot from the Canvas again.
How come my maps snapshot is removed from the canvas as soon as i call this line?:
canvas.drawBitmap(backBitmap, 0, 0, null);
Entire function:
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
#Override
public void onSnapshotReady(Bitmap snapshot) {
try {
view.setDrawingCacheEnabled(true);
Bitmap backBitmap = view.getDrawingCache();
Bitmap bmOverlay = Bitmap.createBitmap(backBitmap.getWidth(), backBitmap.getHeight() - DpConverter.dpToPx(50), backBitmap.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(snapshot, 0, mapView.getTop() + getStatusBarHeight(view), null);
canvas.drawBitmap(backBitmap, 0, 0, null);
FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/AppScreenshots/" + name);
bmOverlay.compress(Bitmap.CompressFormat.PNG, 90, out);
view.setDrawingCacheEnabled(false);
} catch (Exception e) {
e.printStackTrace();
}
}
};

how to draw text on image view android

I have an app that calculate time of phone usage and you can share it on social networks, instead of normal gettext() I want to put the results on an image and save it to phone. How can I create an image that I can save to the phone that includes custom text?
What you want to do is to paint to a Canvas that's linked to a Bitmap, and save the bitmap. Here's a few bits of code that you should be able to string together to make it work. Note that you'll have to still add the paining to the canvas, in the getBitmap() function.
private Bitmap getBitmap() {
Bitmap bitmap = Bitmap.createBitmap(mPieToss.getWidth(),
mPieToss.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
// Draw things to your canvas. They will be included as your BitMap, which is saved later on
return bitmap;
}
public void save() {
Bitmap bitmap = getBitmap();
File path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String filename = "Imagen_" + timestamp + ".jpg";
File file = new File(path, filename);
FileOutputStream stream;
// This can fail if the external storage is mounted via USB
try {
stream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, stream);
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mUri = Uri.fromFile(file);
bitmap.recycle();
}
First of all convert your layout to bitmap:
View contentLayout; // your layout with bavkground image and TextView
Bitmap bitmap = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
content.draw(canvas);
Now you can save it to the file:
FileOutputStream fos = new FileOutputStream(fileName, false);
bitmap.compress(Bitmap.CompressFormat.PNG, 75, fos);
fos.flush();
fos.close();

Saving canvas to bitmap on Android

I'm having some difficulty with regards to placing the contents of a Canvas into a Bitmap. When I attempt to do this, the file gets written with a file size of around 5.80KB but it appears to be completely empty (every pixel is '#000').
The canvas draws a series of interconnected lines that are formed by handwriting. Below is my onDraw for the View. (I'm aware that it's blocking the UI thread / bad practices/ etc.., however I just need to get it working)
Thank you.
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
if (IsTouchDown) {
// Calculate the points
Path currentPath = new Path();
boolean IsFirst = true;
for(Point point : currentPoints){
if(IsFirst){
IsFirst = false;
currentPath.moveTo(point.x, point.y);
} else {
currentPath.lineTo(point.x, point.y);
}
}
// Draw the path of points
canvas.drawPath(currentPath, pen);
// Attempt to make the bitmap and write it to a file.
Bitmap toDisk = null;
try {
// TODO: Get the size of the canvas, replace the 640, 480
toDisk = Bitmap.createBitmap(640,480,Bitmap.Config.ARGB_8888);
canvas.setBitmap(toDisk);
toDisk.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("arun.jpg")));
} catch (Exception ex) {
}
} else {
// Clear the points
currentPoints.clear();
}
}
I had similar problem and i've got solution. Here full code of a task /don't forget about android.permission.WRITE_EXTERNAL_STORAGE permission in manifest/
public Bitmap saveSignature(){
Bitmap bitmap = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
this.draw(canvas);
File file = new File(Environment.getExternalStorageDirectory() + "/sign.png");
try {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
first create a blank bitmap , then create a canvas with that blank bitmap
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bitmap_object = Bitmap.createBitmap(width, height, conf);
Canvas canvas = new Canvas(bitmap_object);
now draw your lines on canvas
Path currentPath = new Path();
boolean IsFirst = true;
for(Point point : currentPoints){
if(IsFirst){
IsFirst = false;
currentPath.moveTo(point.x, point.y);
} else {
currentPath.lineTo(point.x, point.y);
}
}
// Draw the path of points
canvas.drawPath(currentPath, pen);
Now access your bitmap via bitmap_object
You'll have to draw after setting the bitmap to the canvas. Also use a new Canvas object like this:
Canvas canvas = new Canvas(toDisk);
canvas.drawPath(currentPath, pen);
toDisk.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(new File("arun.png")));
I recommend using PNG for saving images of paths.
you must call canvas.setBitmap(bitmap); before drawing anything on Canvas. After calling canvas.setBitmap(bitmap); draw on Canvas and then save the Bitmap you passed to Canvas.
May be
canvas.setBitmap(toDisk);
is not in correct place.
Try this :
toDisk = Bitmap.createBitmap(640,480,Bitmap.Config.ARGB_8888);
toDisk.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("arun.jpg")));
canvas.setBitmap(toDisk);

Android taking a screenshot - partial black Google map

Sometimes it works, sometimes it doesn't. I am sharing this picture on Facebook, and sometimes it is ok:
And sometimes it is partial black (only the Google map!):
I have a separate thread doing this screenshot:
new Thread() {
#Override
public void run() {
// Get root view
View view = mapView.getRootView();
view.setDrawingCacheEnabled(true);
// Create the bitmap to use to draw the screenshot
final Bitmap bitmap = Bitmap.createBitmap(
getWindowManager().getDefaultDisplay().getWidth(), getWindowManager().getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_4444);
final Canvas canvas = new Canvas(bitmap);
// Get current theme to know which background to use
final Theme theme = activity.getTheme();
final TypedArray ta = theme
.obtainStyledAttributes(new int[] { android.R.attr.windowBackground });
final int res = ta.getResourceId(0, 0);
final Drawable background = activity.getResources().getDrawable(res);
// Draw background
background.draw(canvas);
// Draw views
view.draw(canvas);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
Bundle params = new Bundle();
params.putByteArray("source", b);
params.putString("message", "genie in a bottle");
try {
//String resp =
facebook.request("me/photos", params, "POST");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}.start();
You can create the Bitmap object directly from the screen using:
bitmap = Bitmap.createBitmap(view.getDrawingCache());
Regards.

How to Save a PictureDrawable as a JPEG/PNG file in Android

I have PictureDrawable that I wish to save as an image (JPEG/PNG) but I can't seem to find any information how to go about this.
I tried this but it does not seem to work
PictureDrawable myDrawable = GetPictureDrawable();
Bitmap bitmap = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);
myDrawable.draw(new Canvas(bitmap));
bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream("/MyLocation/MyImage.jpg"));
What am I doing wrongly?
//Convert PictureDrawable to Bitmap
private static Bitmap pictureDrawable2Bitmap(PictureDrawable pictureDrawable){
Bitmap bitmap = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(),pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(pictureDrawable.getPicture());
return bitmap;
}

Categories