Friday, May 17, 2013

Insert Image Into Table From A Directory.

1. CONNECT AS SYSDBA IN YOUR DATABASE FOR CREATE A DIRECTORY WHERE HAVE OUR IMAGE
=========================================================================

SQL> conn sys /as sysdba
Enter password:
Connected.

2. CREATE A DIRECTORY FOR COLLECT IMAGE FROM DIRECTORY
=========================================================================

SQL> CREATE OR REPLACE DIRECTORY
  2  IMAGE_DIR AS
  3  'D:\IMAGE\';

Directory created.

3. GIVEN DIRECTORY ACCES PERMITION TO USER
=========================================================================

SQL> GRANT READ, WRITE ON DIRECTORY IMAGE_DIR TO MICR;

Grant succeeded.

4. CONNECTING SPECTFIC USER FOR INSERTING IMAGE
=========================================================================

SQL> conn micr/micr;
Connected.

5. CREATING A FUNCTION FOR CONVERT IMAGE TO BLOB
=========================================================================

SQL> CREATE OR REPLACE FUNCTION FUN_IMAGE_TO_BLOB (
  2     P_IMAGE   IN   VARCHAR2,
  3     P_DIR    IN   VARCHAR2
  4  )
  5     RETURN BLOB
  6  IS
  7     fblob          BLOB;
  8     thebfile       BFILE;
  9     bsrc_offset    NUMBER := 1;
 10     bdest_offset   NUMBER := 1;
 11  BEGIN
 12     DBMS_LOB.createtemporary (fblob, FALSE, DBMS_LOB.SESSION);
 13     thebfile := BFILENAME (P_DIR, P_IMAGE);
 14     DBMS_LOB.fileopen (thebfile);
 15     DBMS_LOB.loadblobfromfile (dest_lob         => fblob,
 16                                src_bfile        => thebfile,
 17                                amount           => DBMS_LOB.getlength (thebfile),
 18                                dest_offset      => bdest_offset,
 19                                src_offset       => bsrc_offset
 20                               );
 21     DBMS_LOB.fileclose (thebfile);
 22     RETURN fblob;
 23  EXCEPTION
 24     WHEN OTHERS
 25     THEN
 26        RETURN NULL;
 27  END;
 28  /

Function created.

6. CREATING A TABLE FOR INSERT IMAGE
=========================================================================

SQL> CREATE TABLE TEST_IMAGE(ID NUMBER, PHATO BLOB);

Table created.

7. INSERTING IMAGE INTO DATABASE FROM A DIRECTORY

=========================================================================

SQL> INSERT INTO TEST_IMAGE(ID, PHATO) VALUES(10, FUN_IMAGE_TO_BLOB('ORA.jpg','IMAGE_DIR'));

1 row created.

SQL>COMMIT;

1 comment: