Drag and drop to other applications and OS? - drag-and-drop

I'm using JavaFX's Drag and Drop system in my application, and it has been working well so far.
Now I want to support drag and drop to outside applications, eg. dragging files from my application to the explorer. How would I achieve that?

I've achieved what you described by using:
Vector<File> files = new Vector<File>();
private ClipboardContent filesToCopyClipboard = new ClipboardContent();
...
final ObjectWithAReturnablePathField draggableObj = new ObjectWithAReturnablePathField();
...
draggableObj.setOnDragDetected(new EventHandler<MouseEvent>()
{
#Override
public void handle(MouseEvent me)
{
Dragboard db = draggableObj.startDragAndDrop(TransferMode.ANY);
try
{
File f = new File(new URI(draggableObj.getFilePath()));
files.add(f);
filesToCopyClipboard.putFiles(files);
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
db.setContent(filesToCopyClipboard);
me.consume();
}
});
draggableObj.setOnDragDone(new EventHandler<DragEvent>()
{
#Override
public void handle(DragEvent me)
{
me.consume();
}
});
Which means:
It's possible to achieve file transference between JavaFX 2 and a native application by filling a ClipboardContent with a list using the TransferMode.ANY on the setOnDragDetected method of any Draggable Object (Any Node) which can return a Path for a file. In my case, I've created a class called Thumb extending ImageView and (among others things) I made a method called getFilePath() which returns the Path from the Image used to initialize the ImageView(). I'm sorry BTW for the poor example and the poor english, but I'm running out of time to give a more detailed answer as of now. I hope it helps. Cheers

Here is a sample source for an action listener on an ImageView image extraction to OS' explorer (With a custom process for jpg image to remove alpha-channel to display it correctly):
inputImageView.setOnDragDetected(new EventHandler <MouseEvent>() {
#Override
public void handle(MouseEvent event) {
// for paste as file, e.g. in Windows Explorer
try {
Clipboard clipboard Clipboard.getSystemClipboard();
Dragboard db = inputImageView.startDragAndDrop(TransferMode.ANY);
ClipboardContent content = new ClipboardContent();
Image sourceImage = inputImageView.getImage();
ImageInfo imageInfo = (ImageInfo) inputImageView.getUserData();
String name = FilenameUtils.getBaseName(imageInfo.getName());
String ext = FilenameUtils.getExtension(imageInfo.getName());
///Avoid get "prefix lenght too short" error when file name lenght <= 3
if (name.length() < 4){
name = name+Long.toHexString(Double.doubleToLongBits(Math.random()));;
}
File temp = File.createTempFile(name, "."+ext);
if (ext.contentEquals("jpg")|| ext.contentEquals("jpeg")){
BufferedImage image = SwingFXUtils.fromFXImage(sourceImage, null); // Get buffered image.
BufferedImage imageRGB = new BufferedImage(image.getWidth(),image.getHeight(),
BufferedImage.OPAQUE);
Graphics2D graphics = imageRGB.createGraphics();
graphics.drawImage(image, 0, 0, null);
ImageIO.write(imageRGB, ext, temp);
graphics.dispose();
ImageIO.write(imageRGB,
ext, temp);
}else{
ImageIO.write(SwingFXUtils.fromFXImage(sourceImage, null),
ext, temp);
}
content.putFiles(java.util.Collections.singletonList(temp));
db.setContent(content);
clipboard.setContent(content);
event.consume();
temp.deleteOnExit();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
});
With the help of use of an Object that is passed to the imageView's setUserData method, it helps me to retrieve database id and pic name:
public class ImageInfo {
private String imageInfo;
private int inputId;
#Override
public String toString() {
return imageInfo;
}
public ImageInfo(String imageInfo, int inputId) {
this.imageInfo = imageInfo;
this.inputId = inputId;
}
public String getName() {
return imageInfo;
}
public void setName(String imageInfo) {
this.imageInfo = imageInfo;
}
public int getIndex() {
return inputId;
}
public void setIndex(int areaindex) {
this.inputId = inputId;
}
}
I hope it will help somenone at an expected time :-)
Regards

Related

Pass data from android to flutter

I have added my Android side code:
I know that I need to use a platform channel to pass data,I am unable to figure out:
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends AppCompatActivity {
private Button Btn;
// Intent defaultFlutter=FlutterActivity.createDefaultIntent(activity);
String path;
private Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btn = findViewById(R.id.btn);
isStoragePermissionGranted();
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
path=takeScreenshot();
// activity.startActivity(defaultFlutter);
}
});
//write flutter xode here
//FlutterActivity.createDefaultIntent(this);
}
private String takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
Log.d("path",mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
return mPath;
///openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
return "Error";
}
}
public boolean isStoragePermissionGranted() {
String TAG = "Storage Permission";
if (Build.VERSION.SDK_INT >= 23) {
if (this.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission is granted");
return true;
} else {
Log.v(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
}
I will receive a file from the android side, upon receiving I need to display it in a flutter. I also need to use cached engine for transferring data as normally it would cause a delay
You can use the cached engine, this will help me cover up for the delay.
Then you can add a invoke method onpressed that you can send method name and the data you want to pass.
On flutter side,you can create a platform and invoke method through which you can receive requirements and further process it,

How do I find which image field in PDF has image inserted and which one has no images attached using PDFbox 1.8.11?

I have a PDF that has image fields inside it. I am not using a PDPushButton with javascript to attach pictures because if I do that the button's top layer gets replaced with the picture that I am attaching which is not what I want. So I am explicitly using a ImageField that is available in Adobe LiveCycle Designer. I am able to extract the files attached on it using PDFBox but I am not able to find any way of seeing which image fields have files attached to them and which ones do not. For example if I have the following code here:
ImageField[1], ImageField[2], ImageField[3]
I want to see something like
ImageField[1]: null,
ImageField[2]: true,
ImageField[3]: trueenter code here
etc assuming ImageField[2] and ImageField[3] has images attached to them.
Below is the code that I was working on:
I have a constant:
Then I am looping through the whole set of image field names and see which field is a instance of PDXObjectImage and then if it is a PDXObjectImage then I check if that object.getRGBImage().getHeight() > 0 assuming that only files uploaded have a height > 1 which means a file has been attached.
private static String[] IMAGE_FIELD_ROW = {"ImageField1[0]","ImageField2[0]",....} => 100 rows of string values such as "ImageField3[0]", "ImageField4[0]", ...etc.
for(int i = 0; i<IMAGE_FIELD_ROW.length; i++)
{
if(field.getPartialName().equals(IMAGE_FIELD_ROW[i]))
{
Map<String, PDAppearanceStream> stateAppearances = field.getWidget().getAppearance().getNormalAppearance();
for (Map.Entry<String, PDAppearanceStream> entry: stateAppearances.entrySet())
{
PDAppearanceStream appearance = entry.getValue();
PDResources resources = appearance.getResources();
if (resources == null)
return;
Map<String, PDXObject> xObjects = resources.getXObjects();
if (xObjects == null)
return;
for (Map.Entry<String, PDXObject> entryNew : xObjects.entrySet())
{
PDXObject xObject = entryNew.getValue();
System.out.println("printing out the xobject name: "+ entryNew.getKey());
if (xObject instanceof PDXObjectForm)
{
PDXObjectForm form = (PDXObjectForm)xObject;
PDResources resources2 = form.getResources();
if (resources2 == null)
return;
Map<String, PDXObject> xObjects2 = resources2.getXObjects();
if (xObjects2 == null)
{
return;
}
for (Map.Entry<String, PDXObject> entry2 : xObjects2.entrySet())
{
PDXObject xObject2 = entry2.getValue();
if (xObject2 instanceof PDXObjectForm)
{
continue;
}
else if (xObject2 instanceof PDXObjectImage)
{
PDXObjectImage ig = (PDXObjectImage)xObject2;
if(ig.getRGBImage().getHeight() > 0)
{
images.put(field.getPartialName(), "true");
}
else
{
images.put(field.getPartialName(), null);
}
//imageIds.add(imageId);
}
else
{
continue;
}
}
}
}
}
}
}
Images is a map variable: Mapimages.
Also my code file is large and so I didn't want to overwhelm anybody by pasting the whole file. Below is the dropbox link for the sample PDF file that I am using:
https://www.dropbox.com/s/g2wqm8ipsp8t8l5/GSA%20500%20PDF_v4.pdf?dl=0
Your PDF is a hybrid AcroForm/XFA document; where the XFA part uses fields with an imageEdit user interface, the AcroForm part uses pushbutton fields.
Thus, it allows you two ways to check whether an image field is set: Either you look at the AcroForm buttons and inspect their appearances for images, or you retrieve the XFA XML and inspect that.
Checking the XFA XML
Initially I did overlook the PDFBox version in the question title and implemented this for PDFBox 2.0.x. As it turns out, though, the identical code can be used for PDFBox 1.8.11, merely some additional exceptions may be thrown and, therefore, must be considered.
The latter option, inspecting the XFA XML, actually is a bit easier for the document at hand. Simply search the XML for an element with the name in question and check its contents. As an additional sanity check one can verify the content type attribute of the element:
boolean isFieldFilledXfa(Document xfaDom, String fieldName) {
NodeList fieldElements = xfaDom.getElementsByTagName(fieldName);
for (int i = 0; i < fieldElements.getLength(); i++) {
Node node = fieldElements.item(i);
if (node instanceof Element) {
Element element = (Element) node;
if (element.getAttribute("xfa:contentType").startsWith("image/")) {
return element.getTextContent().length() > 0;
}
}
}
return false;
}
(CheckImageFieldFilled helper method)
With it you can check your document:
PDDocument document = PDDocument.load(SOURCE);
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
Document xfaDom = acroForm.getXFA().getDocument();
System.out.println("Filled image fields from ImageField1..ImageField105:");
for (int i=1; i < 106; i++) {
if (isFieldFilledXfa(xfaDom, "ImageField" + i)) {
System.out.printf("* ImageField%d\n", i);
}
}
(CheckImageFieldFilled test method testCheckXfaGsa500Pdf_v4)
The output:
Filled image fields from ImageField1..ImageField105:
* ImageField1
* ImageField3
* ImageField6
Checking the AcroForm Appearances
The implementation here only works as is for PDFBox 2.0.x. The structure of the content stream parser classes has been considerably overhauled in 2.0.0, making a back-port of this code to 1.8.x a bit tedious.
To check whether the push button appearance actually shows an image (and not only has an image in its resources), one can use a simple PDFGraphicsStreamEngine subclass like this:
public class WidgetImageChecker extends PDFGraphicsStreamEngine
{
public WidgetImageChecker(PDAnnotationWidget widget) {
super(widget.getPage());
this.widget = widget;
}
public boolean hasImages() throws IOException {
count = 0;
PDAppearanceStream normalAppearance = widget.getNormalAppearanceStream();
processChildStream(normalAppearance, widget.getPage());
return count != 0;
}
#Override
public void drawImage(PDImage pdImage) throws IOException {
count++;
}
#Override
public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3) throws IOException { }
#Override
public void clip(int windingRule) throws IOException { }
#Override
public void moveTo(float x, float y) throws IOException { }
#Override
public void lineTo(float x, float y) throws IOException { }
#Override
public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3) throws IOException { }
#Override
public Point2D getCurrentPoint() throws IOException { return null; }
#Override
public void closePath() throws IOException { }
#Override
public void endPath() throws IOException { }
#Override
public void strokePath() throws IOException { }
#Override
public void fillPath(int windingRule) throws IOException { }
#Override
public void fillAndStrokePath(int windingRule) throws IOException { }
#Override
public void shadingFill(COSName shadingName) throws IOException { }
final PDAnnotationWidget widget;
int count = 0;
}
(CheckImageFieldFilled helper class)
With it you can create a check method like this:
boolean isFieldFilledAcroForm(PDAcroForm acroForm, String fieldName) throws IOException {
for (PDField field : acroForm.getFieldTree()) {
if (field instanceof PDPushButton && fieldName.equals(field.getPartialName())) {
for (final PDAnnotationWidget widget : field.getWidgets()) {
WidgetImageChecker checker = new WidgetImageChecker(widget);
if (checker.hasImages())
return true;
}
}
}
return false;
}
(CheckImageFieldFilled helper method)
and use it like this:
PDDocument document = PDDocument.load(SOURCE);
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
System.out.println("Filled image fields (AcroForm) from ImageField1..ImageField105:");
for (int i=1; i < 106; i++) {
if (isFieldFilledAcroForm(acroForm, "ImageField" + i + "[0]")) {
System.out.printf("* ImageField%d\n", i);
}
}
(CheckImageFieldFilled test testCheckAcroFormGsa500Pdf_v4)
The output, just like above:
Filled image fields (AcroForm) from ImageField1..ImageField105:
* ImageField1
* ImageField3
* ImageField6

GWT image get from server

when I implemented as given here but for not working
my implementation is
ServerSide:
File f = fileFromDatabase // from database the fileName is india.png
DataInputStream din = new DataInputStream(new FileInputStream(f));
din.readFully(data);
din.close();
String base64 = Base64Utils.toBase64(data);
String[] s = filename.split("\\.");
base64 = "data:" + "india/png" + ";base64," + base64;
or
base64 = "data:image/png;base64," + base64;
return base64;
clientSide:
imageService.getImageData(new AsyncCallback() {
#Override
public void onSuccess(String imageData) {
Image image = new Image(imageData);
Canvas.addChild(image);
//this Canvas class addItem into com.smartgwt.client.widgets.Window
}
#Override
public void onFailure(Throwable caught) {
}
}
client side imageData stirng is <image class="gwt-Image src=sume big string starts with "data:image/png;base64,someSting......>"
eventhough client side could not see the image.
Please clear my doubt
Thanks in advance
When you get the base64 string from the server you need to add a load handler on the image in the DOM. The way I've done it is to attach it to the DOM and hide it as in the below code.
/** get events preview from server, attach to the DOM and store in 'preview'
* #param handler option to pass a custom load handler
*/
private void get_preview(LoadHandler handler) {
final LoadHandler load_handler = handler;
server.getPreviewImage(user, data, new AsyncCallback<String>() {
#Override
public void onFailure(Throwable caught) {
log.info("getPreviewImage: " + error);
}
#Override
public void onSuccess(String result) {
preview = null;
if (result != null) {
ImageElement ie = doc.createImageElement();
preview = Image.wrap(ie);
preview.setVisible(false);
doc.getElementById("imagedummy").removeAllChildren();
doc.getElementById("imagedummy").appendChild(preview.getElement());
// add load handler to DOM image before being able to use
if (load_handler == null) {
preview.addLoadHandler(new LoadHandler() {
#Override
public void onLoad(LoadEvent event) {
display_preview();
}
});
} else {
preview.addLoadHandler(load_handler);
}
preview.setUrl(result);
}
}
});
}
/** Displays the preview on the canvas.
* Resizes canvas if necessary and sets zoom
*/
private void display_preview() {
EventSize size = data.getEventSize();
canvas.canvas.setCoordinateSpaceWidth(size.width);
canvas.canvas.setCoordinateSpaceHeight(size.height);
float zoom = Float.parseFloat(preview_zoom.getSelectedValue());
canvas.canvas.setPixelSize((int)(size.width * zoom), (int)(size.height * zoom));
if (preview != null) {
ImageElement elem = ImageElement.as(preview.getElement());
canvas.canvas.getContext2d().drawImage(elem, 0, 0);
}
}

imagej image type conversion

I am new to java programing.
I am trying to write a java application using netbeans that uses imagej jar to open a dicom image & process it. I was able to do that using the following java code:
public class user_interface extends java.awt.Frame {
/** Creates new form user_interface */
public user_interface() {
initComponents();
}
private void initComponents() {
btn_open_image = new java.awt.Button();
btn_invert_image = new java.awt.Button();
slbl_display = new javax.swing.JLabel();
setBackground(java.awt.Color.orange);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
btn_open_image.setLabel("Open Image");
btn_open_image.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn_open_imageMouseClicked(evt);
}
});
btn_open_image.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_open_imageActionPerformed(evt);
}
});
add(btn_open_image, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, 80, -1));
btn_invert_image.setLabel("Invert Image");
btn_invert_image.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn_invert_imageMouseClicked(evt);
}
});
add(btn_invert_image, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 150, 80, -1));
slbl_display.setBackground(new java.awt.Color(51, 51, 51));
add(slbl_display, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 60, -1, -1));
pack();
}// </editor-fold>
/**
* Exit the Application
*/
private void exitForm(java.awt.event.WindowEvent evt) {
System.exit(0);
}
private ImagePlus IPL_image;
private ImageJ ImageJ_image;
private ImageJ CovImageJ_image;
private ImageProcessor ip;
private Image AWT_image;
private ImageIcon AWT_icon;
private void btn_open_imageMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
String MacroName ="C:\\Program Files\\ImageJ\\macros\\RadFz\\DrawGraticule(Worksfine).txt";
String ImgName = "G:\\PV-QA Images\\01-31-2016\\6MV-FS-OF\\RI\\5x5-6MV-MLC.dcm";
//(01) open image
IPL_image = IJ.openImage(ImgName);
int ImgType = IPL_image.getType();
System.out.println("Image Type = " + ImgType);
//IJ.runMacroFile(MacroName);
//(02) pass it to processor to acess each pixel
// ip.convertToColorProcessor();
ip = IPL_image.getProcessor();
//(03) reset the image window & level
ip.resetMinAndMax();
//get width & height
int imgWdth = ip.getWidth();
int imgHgth = ip.getHeight();
// set line color and width
ip.setColor(Color.red);
ip.setLineWidth(3);
ip.drawLine(0, imgHgth/2, imgWdth, imgHgth/2);
ip.drawLine(imgWdth/2, 0, imgWdth/2, imgHgth);
//IPL_image.show(); // Display image in imagej window
//String IIP = IJ.runMacroFile(MacroName);
//convert image from imagej format to one that you can
//display in image container
AWT_image = ip.createImage();
AWT_icon = new ImageIcon(AWT_image);
slbl_display.setIcon(AWT_icon);
System.out.println("Width = " + imgWdth + " pixels");
System.out.println("Height = " + imgHgth + " pixels");
GetDICOMTagVal("300A,012C");
}
private void btn_invert_imageMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
ip.invert();
AWT_image = ip.createImage();
AWT_icon = new ImageIcon(AWT_image);
slbl_display.setIcon(AWT_icon);
}
private void btn_open_imageActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void GetDICOMTagVal(String DICOMTag) {
String imgInfoStr = IPL_image.getInfoProperty();
//"0002,0003" "300A,012C"
System.out.println("imgInfoStr = \n"+ imgInfoStr );
String InfoLines[];
InfoLines = split(imgInfoStr, "\n");
//System.out.println(" Number of lines = " + InfoLines.length);
int i;
for (i =0; i<InfoLines.length; i++){
//System.out.println(i+" -->" + InfoLines[i].startsWith(DICOMTag));
if(InfoLines[i].startsWith(DICOMTag)) {
String Tag;
Tag = InfoLines[i].substring(DICOMTag.length());
System.out.println(DICOMTag + " = " + Tag);
} else {
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new user_interface().setVisible(true);
}
});
}
// Variables declaration - do not modify
private java.awt.Button btn_invert_image;
private java.awt.Button btn_open_image;
private javax.swing.JLabel slbl_display;
// End of variables declaration
}
I am able to open the image and process it (draw on it) using black lines only. That is because the image is opened as an 8 bit gray image. I am not sure how to convert image to RGB. The convertToRGB() is available in the ij package in the processing folder in the image converter class.
How can I do that?
Indeed as you said, the abstract class ImageProcessor has a method convertToRGB():
public ImageProcessor convertToRGB()
{
if ( type == RGB ) return ip ;
ImageProcessor ip2 = ip.convertToByte(doScaling) ;
return new ColorProcessor(ip2.createImage()) ;
}
It does exactly what you need: convert a ByteProcessor (8 bits) into a ColorProcessor (24 bits).

How can I get the column number in a SWT table in Eclipse RCP?

My question is How can we find the currently selected column number in the selected row of a SWT Table in Eclipse RCP?
Inside a Listener - e.g. for SWT.Selection - you can use viewer.getCell(...) as illustrated in the following example:
myTableViewer.getTable().addListener(SWT.Selection, new Listener() {
#Override
public void handleEvent(Event event) {
Point p = new Point(event.x, event.y);
ViewerCell cell = myTableViewer.getCell(p);
int columnIndex = cell.getColumnIndex();
//...
}
});
If you want to be sure that the columnindex is updated prior to calling the selectionlistener, then the mousedown event will also work fine:
table.addMouseListener( new MouseAdapter() {
private static final long serialVersionUID = 1L;
#Override
public void mouseDown(MouseEvent event) {
try {
Point p = new Point(event.x, event.y);
ViewerCell cell = viewer.getCell(p);
selectedColumn = cell.getColumnIndex();
} catch (Exception e) {
e.printStackTrace();
}
}
});