• Познакомьтесь с пентестом веб-приложений на практике в нашем новом бесплатном курсе

    «Анализ защищенности веб-приложений»

    🔥 Записаться бесплатно!

  • CTF с учебными материалами Codeby Games

    Обучение кибербезопасности в игровой форме. Более 200 заданий по Active Directory, OSINT, PWN, Веб, Стеганографии, Реверс-инжинирингу, Форензике и Криптографии. Школа CTF с бесплатными курсами по всем категориям.

Фото С Вебкамеры В Richtext

dimat

Well-known member
31.07.2008
508
0
BIT
0
Всем привет!
Собственно есть у кого идеи как по нажатию кнопки на форме(для примера) сделать снимок на вебкамеру и запихнуть фото в RichText как картинку(не как вложение)? Это задача максимум.
Задача минимум: по кнопке выбрать файл фотографии и вставить ее в Richtext.
 

savl

Lotus Team
28.10.2011
2 597
310
BIT
159
dimat
Чтобы по кнопке из файла вставить фото, как картинку:
Код:
@Command([EditGotoField];"FOTO");
@PostedCommand([FileImport])
А вот с камеры... наверное через API в буфер картинку сохранить и потом вставить из буфера.
 

dimat

Well-known member
31.07.2008
508
0
BIT
0
savl Спасибо.
В буфер имеется ввиду виндовый?
Через api Прог. обеспечения Камеры?

да и, если просто вставить картинку по нажатию кнопки, хотелось бы изменить ее размер это уже наверное через dxl как то?
 

savl

Lotus Team
28.10.2011
2 597
310
BIT
159
Ну в целом да, с камеры не просто так.
для windows
Еще вариант через софт от камеры, COM скорее всего, либо внешняя DLL



Добавлено: Про размер... Ну да, через DXL можно поменять.
 

dimat

Well-known member
31.07.2008
508
0
BIT
0
alexas1
Не совсем понимаю, вернее совсем не понимаю, как их использовать?
 

lmike

нет, пердело совершенство
Lotus Team
27.08.2008
7 933
609
BIT
177
камеры д.б. UVC
это шобы с дровами не долбаться
затем
или (на стековерфлоу упоминается)
суваем файло в DXL, кажем юзверю
вот ежели понадобится морду выцеливать - нужно тоды аплет сувать либо окно со свингом
 

alexas1

Green Team
10.04.2014
1 202
225
BIT
34
Не совсем понимаю, вернее совсем не понимаю, как их использовать?
Это проблема.

Тогда c другой стороны, c примерами и проще:<div class="sp-wrap"><div class="sp-head-wrap"><div class="sp-head folded clickable">В классике на LS</div></div><div class="sp-body"><div class="sp-content">
Код:
Set devmgr = createobject( "WIA.DeviceManager")

For c = 1 To devmgr.DeviceInfos.Count
If devmgr.DeviceInfos( c).Type = 2 Or devmgr.DeviceInfos( c).Type = 3 Then ' 2 = Camera, 3 = Video
Set dev = devmgr.DeviceInfos( c).Connect()
Set cdg = Createobject( "WIA.CommonDialog")

' First remove all buffered images from previous sessions
TempPath$ = dev.Properties( 24).Value
TempFilter$ = TempPath$ + "\*.jpg"
fileName$ = Dir$( TempFilter$, 0)
Do While fileName$ <> ""
Kill TempPath$ + "\" + fileName$
fileName$ = Dir$()
Loop

Set cdg = Createobject( "WIA.CommonDialog")
Set img = cdg.ShowAcquireImage( _
3, _
1, _
65536, _
"{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}", _
0, _
0, _
0)

' Resize the captured image
Set IP = CreateObject("WIA.ImageProcess")
IP.Filters.Add IP.FilterInfos("Scale").FilterID
IP.Filters(1).Properties("MaximumWidth") = 200
IP.Filters(1).Properties("MaximumHeight") = 100
Set Img = IP.Apply(Img)

If img Is Nothing Then ' they clicked cancel
Exit Sub
End If

' save the pic to hard disk with the filename D09679A7EF130E7988256FF4000A5265-08-18-2009 03-46-42 PM PDT.jpg
' where those first 32 chars are what's in the DOCID field of the currently open document
Dim dtNow As New NotesDateTime( Now)
strDate$ = dtNow.LocalTime
varDate = Evaluate( |@ReplaceSubstring( "| + strDate$ + |"; ":" : "/"; "-")|)
strDate$ = Cstr( varDate( 0))
Dim uidoc As NotesUIDocument
Dim ws As New NotesUIWorkspace
Set uidoc = ws.CurrentDocument
Dim strFilePath As String

strFilePath = session.GetEnvironmentString( "MyAppTempDirPath") + "\" + uidoc.Document.DOCID( 0) + "-" + strDate$ + ".jpg"
Call img.SaveFile( strFilePath)


Call uidoc.GotoField( "Picture")
Call uidoc.Import( "JPEG Image", strFilePath)
intID = Shell( |cmd /c del "| + strFilePath + |"|)	' delete the temp file from hard disk
Call uidoc.GotoNextField


Exit For ' no need to look for any more devices
End If
Next c
Эта штука будет работать на winXP & win8 - в висте и семёрке wiaaut.dll нету, соответственно бубен в руки
Что бы работало, надо, как минимум, чтобы устройство отобразилось в "Сканерах и камерах" Панели управления Windows.

===================================================================
Ещё из закромов (PlanetLotus вроде)<div class="sp-wrap"><div class="sp-head-wrap"><div class="sp-head folded clickable">Capturing image from camera using getUserMedia() and saving it in a document using XPages</div></div><div class="sp-body"><div class="sp-content">Naveen Maurya

HTML5 introduces a new API navigator.getUserMedia() which allows web applications to access a user’s camera and microphone. This article on HTML5 Rocks and this question on StackOverflow describe how to use it in your web applications.

In this article I will describe how to use navigator.getUserMedia() in your XPage and save the captured image in your Notes document. As of now this demo is supported only on Google Chrome & Mozilla Firefox on desktop and mobile (I have tested it on Andorid only).

HTML5 introduces <video> tag which allow developers access to user’s camera.

<video id="video" style="height:240px;width:320px" autoplay="true"></video>
Next we need to add <canvas> tag and an <image> tag. The image captured from user’s camera is drawn on to <canvas>. We then get the Base64 encoded image from <canvas> put it into our <image> (JavaScript code to do that comes later in article).

<canvas id="canvas" style="display: none; height:240px; width:320px"></canvas>
<xp:image url="/.ibmxspres/dojoroot/dojo/resources/blank.gif" id="capturedImage" style="height:240px;width:320px"></xp:image>
Notice that the <canvas> is hidden.

I am also going to add a text area to my XPage where I will store the Base64 encoded text of the captured image which later would be converted into image using Java (code for that comes later in article). While developing applications you can hide this text area using CSS.

<xp:inputTextarea id="taImageBase64"></xp:inputTextarea>
And finally we need a button to take snapshot from camera.

<xp:button id="btnCapture" value="Fire up my camera!"></xp:button>
In our JavaScript code we initialize all the variables we would be using.

var video = document.getElementById("video"); // Video
var canvas = document.getElementById("canvas"); // Canvas
var ctx = canvas.getContext("2d"); // Used to draw image from video stream on to canvas
var localMediaStream = null;
var capturedImage = document.getElementById("#{id:capturedImage}"); // Image
To get the video stream from camera we use navigator.getUserMedia. As of now navigator.getUserMedia is vendor prefixed so we test which one is supported.

// Get the video from the webcam, this is currently prefixed for different browsers, so we need to test which one is supported
navigator.getMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia || navigator.msGetUserMedia);
Now we need to turn on the camera, get the video stream and show it in <video> tag. The code to get the video stream slightly differs from browser to browser.

navigator.getMedia({
video : true,
audio : false // We do NOT require audio
}, function(stream) {
if (navigator.mozGetUserMedia) { // For Firefox
video.mozSrcObject = stream;
} else { // For Chrome
var vendorURL = window.webkitURL || window.URL;
video.src = vendorURL.createObjectURL(stream);
}
video.play(); // Start the video in webcam
localMediaStream = stream; // Store the video stream
button.textContent = "Say Cheese!";
}, function(e) {
alert("An error occured! " + (e.name || e));
});
Once we have the video stream we can draw it on our <canvas>. While drawing we need to make sure that the height and width of our <video> and <canvas> are set to same dimensions otherwise the drawn image gets cropped. To get the Base64 encoded text for image we use canvas.toDataURL.

// Draw on canvas
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;

// Draw on image
capturedImage.height = video.videoHeight;
capturedImage.width = video.videoWidth;
ctx.drawImage(video, 0, 0);// , width, height);
var imageData = canvas.toDataURL("image/png"); // Gets the Base64 encoded text for image
capturedImage.src = imageData;

// Store the Base64 of captured image
document.getElementById("#{id:taImageBase64}").value = imageData;
So our final code for button looks something like this:

var button = document.getElementById("#{id:btnCapture}");
button.addEventListener("click", function(e) {
// Check if browser is supported
if (!navigator.getMedia) {
alert("Your browser does not support video stream.");
return;
}

// If the video stream is working
if (localMediaStream) {
// Draw on canvas
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;

// Draw on image
capturedImage.height = video.videoHeight;
capturedImage.width = video.videoWidth;
ctx.drawImage(video, 0, 0);
var imageData = canvas.toDataURL("image/png"); // Gets the Base64 encoded text for image
capturedImage.src = imageData;

// Store the Base64 of captured image
document.getElementById("#{id:taImageBase64}").value = imageData;
return;
}

// If video stream is NOT working
navigator.getMedia({
video : true,
audio : false // We do NOT require audio
}, function(stream) {
if (navigator.mozGetUserMedia) {
video.mozSrcObject = stream;
} else {
var vendorURL = window.webkitURL || window.URL;
video.src = vendorURL.createObjectURL(stream);
}
video.play(); // Start the video in webcam
localMediaStream = stream; // Store the video stream
button.textContent = "Say Cheese!";
}, function(e) {
alert("An error occured! " + (e.name || e));
});
}, false);
Now we need to convert the Base64 text to image and attach it to our document. For converting Base64 to image we create a Java class and use javax.xml.bind.DatatypeConverter.parseBase64Binary to convert it to binary and then we can attach it to a rich text field in document.

package uk.co.pipalia;

import java.io.ByteArrayInputStream;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import javax.xml.bind.DatatypeConverter;
import lotus.domino.Document;
import lotus.domino.MIMEEntity;
import lotus.domino.MIMEHeader;
import lotus.domino.Session;
import lotus.domino.Stream;
import com.ibm.xsp.model.domino.DominoUtils;
import com.ibm.xsp.page.compiled.ExpressionEvaluatorImpl;

public class SaveBase64Image {
Document targetDoc;
String b64String;

public SaveBase64Image(Document targetDoc) {
// Get the value stored in text area
String valueExpr = "#{java script: getComponent("taImageBase64").getValue();}";
FacesContext facesContext = FacesContext.getCurrentInstance();
ExpressionEvaluatorImpl evaluator = new ExpressionEvaluatorImpl(facesContext);
ValueBinding vb = evaluator.createValueBinding(facesContext.getViewRoot(), valueExpr, null, null);
b64String = (String) vb.getValue(facesContext);

this.targetDoc = targetDoc;
b64String = b64String.replace("data:image/png;base64,", "");
}

public void process() {
if (b64String.trim().equals("")) {
return;
}

try {
// Convert the Base64 string to binary
byte[] imgBytes = DatatypeConverter.parseBase64Binary(b64String);

Session s = DominoUtils.getCurrentSession();
s.setConvertMime(false);

// Create MIME to store the image
MIMEEntity richtext = targetDoc.createMIMEEntity("CapturedImage");
MIMEHeader header = richtext.createHeader("Content-Type");
header.setHeaderVal("multipart/mixed");

MIMEEntity child = richtext.createChildEntity();
header = child.createHeader("Content-Disposition");
header.setHeaderValAndParams("attachment; filename=camerasnap.png");

// Add the image to MIME via stream
Stream stream = s.createStream();
stream.setContents(new ByteArrayInputStream(imgBytes));
child.setContentFromBytes(stream, "image/png", MIMEEntity.ENC_IDENTITY_BINARY);

stream.close();
s.setConvertMime(true);
} catch (Exception e) {
System.out.println("Error in uk.co.pipalia.SaveBase64Image.process()");
e.printStackTrace();
}
}
}
We call this Java class from querySaveDocument event.

<xp:this.data>
<xp:dominoDocument var="cameraImgDoc" formName="fCameraImage">
<xp:this.querySaveDocument><![CDATA[#{java script:var saveImage:uk.co.pipalia.SaveBase64Image = new uk.co.pipalia.SaveBase64Image(currentDocument.getDocument());
saveImage.process();}]]></xp:this.querySaveDocument>
</xp:dominoDocument>
</xp:this.data>
And we ready to take snaps from our webcam.

When you click on the button “Fire up my camera!” browser will ask for your permission. Once the permission is granted you can see your video and take snaps.
Это работает в Хроме и Мозиле. В нотусёвом браузере нет.
Посмотреть вложение CameraAPIDemo.zip
===============================================================
Ещё EZTwain тоже с камерой должен дружить

Примеры для сканера, но это не суть...
 

lmike

нет, пердело совершенство
Lotus Team
27.08.2008
7 933
609
BIT
177
про openCVF
кста - мощная либа:



это о том что распознавание образов в т.ч. возможно
единственное НО - использует JNI (JNA) - нативный код
 

dimat

Well-known member
31.07.2008
508
0
BIT
0
Офигеть сколько всего, спасибо, буду пробовать разбираться.
 
Мы в соцсетях:

Обучение наступательной кибербезопасности в игровой форме. Начать игру!