I created a plot on Canvas. Now I want to add the image to an Excel file.
I know how to get a WritableImage from Canvas and I know that I need an InputStream to write an image in Excel with addPicture(). The problem is how to link these two.
I could save this image to file and then open and load it to Excel, but maybe there is a way to avoid this?
You could use a PipedInputStream/PipedOutputStream to accomplish this:
Image image = ...
BufferedImage bImage = SwingFXUtils.fromFXImage(image, null);
PipedOutputStream pos;
try (PipedInputStream pis = new PipedInputStream()) {
pos = new PipedOutputStream(pis);
new Thread(() -> {
try {
ImageIO.write(bImage, "png", pos);
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
}).start();
workbook.addPicture(pis, Workbook.PICTURE_TYPE_PNG);
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
or you could write the data to a array using ByteArrayOutputStream:
Image image = ...
BufferedImage bImage = SwingFXUtils.fromFXImage(image, null);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(bImage, "png", bos);
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
workbook.addPicture(bos.toByteArray(), Workbook.PICTURE_TYPE_PNG);
Related
I have an activity for add new post, in each post user can select picture from gallery or take picture with camera. My save image method is ok for picture from camera but when I choose a picture from gallery, in my folder just save name of picture with a black picture.
public void saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
img_name = f.getAbsolutePath();
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
And in my RecyclerView shows nothing.
You are just creating a new image file and not saving anything in it .
use following
FileOutputStream fo = new FileOutputStream(f);
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, fo); // bmp is your Bitmap instance
fo.write(bytes.toByteArray());
you are missing this myBitmap.compress(Bitmap.CompressFormat.PNG, 100, fo); so add it.
Let's say that I want to load an shp file, do my stuff on it and save the map as an image.
In order to save an image I am using:
public void saveImage(final MapContent map, final String file, final int imageWidth) {
GTRenderer renderer = new StreamingRenderer();
renderer.setMapContent(map);
Rectangle imageBounds = null;
ReferencedEnvelope mapBounds = null;
try {
mapBounds = map.getMaxBounds();
double heightToWidth = mapBounds.getSpan(1) / mapBounds.getSpan(0);
imageBounds = new Rectangle(0, 0, imageWidth, (int) Math.round(imageWidth * heightToWidth));
} catch (Exception e) {
// Failed to access map layers
throw new RuntimeException(e);
}
BufferedImage image = new BufferedImage(imageBounds.width, imageBounds.height, BufferedImage.TYPE_INT_RGB);
Graphics2D gr = image.createGraphics();
gr.setPaint(Color.WHITE);
gr.fill(imageBounds);
try {
renderer.paint(gr, imageBounds, mapBounds);
File fileToSave = new File(file);
ImageIO.write(image, "png", fileToSave);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
But, let's say I am doing something like this:
...
MapContent map = new MapContent();
map.setTitle("TEST");
map.addLayer(layer);
map.addLayer(shpLayer);
// zoom into the line
MapViewport viewport = new MapViewport(featureCollection.getBounds());
map.setViewport(viewport);
saveImage(map, "/tmp/img.png", 800);
1) The problem is that the zoom level isn't saved on the image file.Is there a way to save it?
2) When I am doing MapViewport(featureCollection.getBounds()); is there a way to extend a little bit the boundaries in order to have a better visual representation?
...
The reason that you aren't saving the map at the current zoom level is that in your saveImage method you have the line:
mapBounds = map.getMaxBounds();
which always uses the full extent of the map, you can change this to
mapBounds = map.getViewport().getBounds();
You can expand a bounding box by something like:
ReferencedEnvelope bounds = featureCollection.getBounds();
double delta = bounds.getWidth()/20.0; //5% on each side
bounds.expandBy(delta );
MapViewport viewport = new MapViewport(bounds);
map.setViewport(viewport );
A quicker (and easier) way to save a map from the GUI is to use a method like this which just saves exactly what is on the screen:
public void drawMapToImage(File outputFile, String outputType,
JMapPane mapPane) {
ImageOutputStream outputImageFile = null;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(outputFile);
outputImageFile = ImageIO.createImageOutputStream(fileOutputStream);
RenderedImage bufferedImage = mapPane.getBaseImage();
ImageIO.write(bufferedImage, outputType, outputImageFile);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (outputImageFile != null) {
outputImageFile.flush();
outputImageFile.close();
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (IOException e) {// don't care now
}
}
}
I have a sm-t300i and im trying to figure out how to print a image from a database. I have the image data but not sure how to plug it in. I have successfuly added a image from the assets but not sure how to from raw image data. Code below is from assets. Also for some reason the image in the code below will not center is there something else i need to do to center the image. Thank you.
AssetManager assetManager = mContext.getAssets();
InputStream istr = null;
try {
istr = assetManager.open("www/img/logo.bmp");
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(istr);
StarBitmap starbitmap = new StarBitmap(bm, false, 200);
commands.add(new byte[] { 0x1b, 0x61, 0x01 }); //align center
commands.add(starbitmap.getImageEscPosDataForPrinting(false,false));
Looks like you can just convert the base64 and make it a bitmap
String imagex = "iVBORw0KGgoAAAANS etc";
Bitmap bm = StringToBitMap(imagex);
StarBitmap starbitmap = new StarBitmap(bm, true, 600);
commands.add(starbitmap.getImageEscPosDataForPrinting(false,true));
public Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte=Base64.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}
}
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();
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.