forked from nhf216/jes-hack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
media.py
2596 lines (2349 loc) · 89.9 KB
/
media.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ORIGINAL COMMENT from JES media.py BELOW
#
# Media Wrappers for "Introduction to Media Computation"
# Started: Mark Guzdial, 2 July 2002
# Revisions:
# 18 June 2003: (ellie)
# Added (blocking)play(AtRate)InRange methods to Sound class
# and global sound functions
# Changed getSampleValue, setSampleValue to give the appearance
# of 1-based indexing
# Added getLeftSampleValue and getRightSampleValue to Sound class
# 14 May 2003: Fixed discrepancy between getMediaPath and setMediaFolder (AdamW)
# 8 Nov: Fixed getSamplingRate (MarkG)
# 1 Nov: Fixed printing pixel
# 31 Oct: Fixed pickAColor (MarkG)
# 30 Oct: Added raises, fixed error messages. Added repaint (MarkG)
# 10 Oct: Coerced value to integer in Sound.setSampleValue (MarkR)
# 2 Oct: Corrected calls in setSampleValueAt (MarkG):
# 30 Aug: Made commands more consistent and add type-checking (MarkG)
# 2 Aug: Changed to getSampleValueAt and setSampleValueAt (MarkG)
# 1 Dec 2005: made max makeEmptySound size 600
# made max makeEmptyPicture dimensions 10000x10000
# fixed the off-by-one error in makeEmptyPicture
# 14 June 2007: (Pam Cutter, Kalamazoo College)
# Fixed off-by-one error in copyInto. Now allows copying
# of same-sized picture, starting at top-left corner
#
# 6 July 2007: (Pam Cutter/Alyce Brady, Kalamazoo College)
# Added flexibility to make an empty picture of a specified color. Added
# additional, 3-parameter constructor to Picture and SimplePicture classes to support this.
# Modified copyInto so that it will copy as much of the source picture as will fit
# Added crop and copyInto methods to Picture class to support these.
#
# 8 July 2007: (Pam Cutter/ Alyce Brady, Kalamazoo College)
# Changed all _class_ comparisons to use isinstance instead so that
# they will work with subclasses as well (e.g., subclasses of Picture
# are still pictures)
# Added getSampleValue, setSampleValue functions with same functionality, but
# more intuitive names, as the getSample, setSample function, respectively.
# Added global getDuration function to return the number of seconds in a sound
#
# 10 July 2007: (Pam Cutter, Kalamazoo College)
# Added a global duplicateSound function
# 11 July 2007: (Pam Cutter, Kalamazoo College)
# Added global addTextWithStyle function to allow users to add text to images
# with different font styles.
#
# 17 July 2007: (Pam Cutter, Kalamazoo College)
# Added 7global addOval, addOvalFilled, addArc and addArcFilled functions.
# Added global getNumSamples function as more meaningful name for getLength of a sound.
#
# 19 July 2007: (Pam Cutter, Kalamazoo College)
# Modified the SoundExplorer class to be consistent with sounds in JES
# starting at sample index 1.
# Modified the PictueExplorer class to initially show color values from
# pixel 1,1, instead of 0,0.
#
# 1 Nov 2007: Added __add__ and __sub__ to Color class (BrianO)
# 29 Apr 2008: Changed makeEmptySound to take an integer number of samples
# Added optional second argument to makeEmptySound for sampleRate
# 6 June 2008: Added a check for forward slash in a directory path in makeMovieFromInitialFile
# This check should work with os.altsep, but it does not work with Jython 2.2.
# This should be fixed again at a later date.
# 27 June 2008: Added optional input to setMediaFolder and setMediaPath.
# Added showMediaFolder and showMediaPath methods.
# 11 July 2007: Removed showMediaFolder and showMediaPath for no-arg version of getMediaPath/getMediaFolder.
# Added generic explore method.
# 15 July 2007: Added no-arg option for setLibPath
# TODO:
## Fix HSV/RGB conversions -- getting a divide by zero error when max=min
import sys
import os
import math
import tempfile
import numbers
#import traceback
#import user
#Don't Use PIL for images
#except one case
import PIL
#import PIL.ImageTk as ImageTk
#from os import system
#from platform import system as platform
#Use Qt for everything
from PyQt4.QtGui import *
from PyQt4.QtCore import *
# Create an PyQT4 application object.
#If we're running in Canopy, there already is one
root = QApplication.instance()
if root is None:
#We're not running in Canopy
#Need to launch a new application
root = QApplication(sys.argv)
#import tkinter
#from tkinter import filedialog
#from tkinter.colorchooser import askcolor
#import threading
#import org.python.core.PyString as String
#root = tkinter.Tk()
#root.withdraw()
#roots = []
# Support a media shortcut
#mediaFolder = JESConfig.getMediaPath()
#if ( mediaFolder == "" ):
mediaFolder = os.getcwd() + os.sep
# Store last pickAFile() opening
_lastFilePath = ""
true = 1
false = 0
#List of things to keep around
keepAround = []
#Check supported image types
suppTypes = QImageReader.supportedImageFormats()
supportedImageTypes = set([])
for typ in suppTypes:
supportedImageTypes.add(str(typ)[2:-1])
#Is the type of this file supported?
def isSupportedImageFormat(fname):
inddot = fname.rfind(".")
if inddot == -1:
tstr = fname
else:
tstr = fname[inddot+1:]
return tstr.lower() in supportedImageTypes
#Error reporting structure
#Lets us refactor error reporting by changing only one line of code!
def reportErrorToUser(errType, msg):
#print(msg)
raise errType(msg)
#Shortcut for ValueError reporting
def repValError(msg):
reportErrorToUser(ValueError, msg)
#Done
def setMediaPath(file=None):
global mediaFolder
if(file == None):
mediaFolder = pickAFolder()
else:
mediaFolder = file
#mediaFolder = getMediaPath()
return mediaFolder
def getMediaPath( filename = "" ):
return mediaFolder + os.sep + filename
#return FileChooser.getMediaPath( filename )
#Done
def setMediaFolder(file=None):
return setMediaPath(file)
#Done
def setTestMediaFolder():
global mediaFolder
mediaFolder = os.getcwd() + os.sep
#Done
def getMediaFolder( filename = "" ):
return getMediaPath(filename)
#Done
def showMediaFolder():
global mediaFolder
print("The media path is currently: ",mediaFolder)
#Done
def getShortPath(filename):
dirs = filename.split(os.sep)
if len(dirs) < 1:
return "."
elif len(dirs) == 1:
return dirs[0]
else:
return (dirs[len(dirs) - 2] + os.sep + dirs[len(dirs) - 1])
#Done
def setLibPath(directory=None):
if(directory == None):
directory = pickAFolder()
if(os.path.isdir(directory)):
sys.path.append(directory)
else:
#print("Note: There is no directory at ",directory)
#raise ValueError
repValError("Note: There is no directory at "+str(directory))
return directory
#This is not actually a media function
#Instead, it lets us print out range objects like in Python 2
def printRange(rng):
print([x for x in rng])
# ##
# ## Global sound functions
# ##
# def makeSound(filename):
# global mediaFolder
# if not os.path.isabs(filename):
# filename = mediaFolder + filename
# if not os.path.isfile(filename):
# #print("There is no file at "+filename)
# #raise ValueError
# repValError("There is no file at "+filename)
# #return Sound(filename)
# #TODO
#
# # MMO (1 Dec 2005): capped size of sound to 600
# # Brian O (29 Apr 2008): changed first argument to be number of samples, added optional 2nd argument of sampling rate
# def makeEmptySound(numSamples, samplingRate = Sound.SAMPLE_RATE):
# if numSamples <= 0 or samplingRate <= 0:
# #print("makeEmptySound(numSamples[, samplingRate]): numSamples and samplingRate must each be greater than 0")
# #raise ValueError
# repValError("makeEmptySound(numSamples[, samplingRate]): numSamples and samplingRate must each be greater than 0")
# if (numSamples/samplingRate) > 600:
# #print("makeEmptySound(numSamples[, samplingRate]): Created sound must be less than 600 seconds")
# #raise ValueError
# repValError("makeEmptySound(numSamples[, samplingRate]): Created sound must be less than 600 seconds")
# #return Sound(numSamples, samplingRate)
# #TODO
# # if size > 600:
# # #print "makeEmptySound(size): size must be 600 seconds or less"
# # #raise ValueError
# # repValError("makeEmptySound(size): size must be 600 seconds or less")
# # return Sound(size * Sound.SAMPLE_RATE)
#
# # Brian O (5 May 2008): Added method for creating sound by duration
# def makeEmptySoundBySeconds(seconds, samplingRate = Sound.SAMPLE_RATE):
# if seconds <= 0 or samplingRate <= 0:
# #print("makeEmptySoundBySeconds(numSamples[, samplingRate]): numSamples and samplingRate must each be greater than 0")
# #raise ValueError
# repValError("makeEmptySoundBySeconds(numSamples[, samplingRate]): numSamples and samplingRate must each be greater than 0")
# if seconds > 600:
# #print("makeEmptySoundBySeconds(numSamples[, samplingRate]): Created sound must be less than 600 seconds")
# #raise ValueError
# repValError("makeEmptySoundBySeconds(numSamples[, samplingRate]): Created sound must be less than 600 seconds")
# #return Sound(seconds * samplingRate, samplingRate)
# #TODO
#
# # PamC: Added this function to duplicate a sound
# def duplicateSound(sound):
# if not isinstance(sound, Sound):
# #print("duplicateSound(sound): Input is not a sound")
# #raise ValueError
# repValError("duplicateSound(sound): Input is not a sound")
# #return Sound(sound)
# #TODO
#
# def getSamples(sound):
# if not isinstance(sound, Sound):
# #print("getSamples(sound): Input is not a sound")
# #raise ValueError
# repValError("getSamples(sound): Input is not a sound")
# # return Samples(sound)
# #return Samples.getSamples(sound)
# #TODO
#
# def play(sound):
# #if not isinstance(sound,Sound):
# # #print "play(sound): Input is not a sound"
# # #raise ValueError
# # repValError("play(sound): Input is not a sound")
# #sound.play()
# pass #TODO
#
# def blockingPlay(sound):
# #if not isinstance(sound,Sound):
# # #print "blockingPlay(sound): Input is not a sound"
# # #raise ValueError
# # repValError("blockingPlay(sound): Input is not a sound")
# #sound.blockingPlay()
# pass #TODO
#
# # Buck Scharfnorth (27 May 2008): Added method for stopping play of a sound
# def stopPlaying(sound):
# #if not isinstance(sound,Sound):
# # #print "stopPlaying(sound): Input is not a sound"
# # #raise ValueError
# # repValError("stopPlaying(sound): Input is not a sound")
# #sound.stopPlaying()
# pass #TODO
#
# def playAtRate(sound,rate):
# #if not isinstance(sound, Sound):
# # #print "playAtRate(sound,rate): First input is not a sound"
# # #raise ValueError
# # repValError("playAtRate(sound,rate): First input is not a sound")
# ## sound.playAtRate(rate)
# #sound.playAtRateDur(rate,sound.getLength())
# pass #TODO
#
# def playAtRateDur(sound,rate,dur):
# #if not isinstance(sound,Sound):
# # #print "playAtRateDur(sound,rate,dur): First input is not a sound"
# # #raise ValueError
# # repValError("playAtRateDur(sound,rate,dur): First input is not a sound")
# #sound.playAtRateDur(rate,dur)
# pass #TODO
#
# #20June03 new functionality in JavaSound (ellie)
# def playInRange(sound,start,stop):
# #if not isinstance(sound, Sound):
# # #print "playInRange(sound,start,stop): First input is not a sound"
# # #raise ValueError
# # repValError("playInRange(sound,start,stop): First input is not a sound")
# ## sound.playInRange(start,stop)
# #sound.playAtRateInRange(1,start-Sound._SoundIndexOffset,stop-Sound._SoundIndexOffset)
# pass #TODO
#
# #20June03 new functionality in JavaSound (ellie)
# def blockingPlayInRange(sound,start,stop):
# #if not isinstance(sound, Sound):
# # #print "blockingPlayInRange(sound,start,stop): First input is not a sound"
# # #raise ValueError
# # repValError("blockingPlayInRange(sound,start,stop): First input is not a sound")
# ## sound.blockingPlayInRange(start,stop)
# #sound.blockingPlayAtRateInRange(1,start-Sound._SoundIndexOffset,stop-Sound._SoundIndexOffset)
# pass #TODO
#
# #20June03 new functionality in JavaSound (ellie)
# def playAtRateInRange(sound,rate,start,stop):
# #if not isinstance(sound,Sound):
# # #print "playAtRateInRAnge(sound,rate,start,stop): First input is not a sound"
# # #raise ValueError
# # repValError("playAtRateInRAnge(sound,rate,start,stop): First input is not a sound")
# #sound.playAtRateInRange(rate,start - Sound._SoundIndexOffset,stop - Sound._SoundIndexOffset)
# pass #TODO
#
# #20June03 new functionality in JavaSound (ellie)
# def blockingPlayAtRateInRange(sound,rate,start,stop):
# #if not isinstance(sound, Sound):
# # #print "blockingPlayAtRateInRange(sound,rate,start,stop): First input is not a sound"
# # #raise ValueError
# # repValError("blockingPlayAtRateInRange(sound,rate,start,stop): First input is not a sound")
# #sound.blockingPlayAtRateInRange(rate, start - Sound._SoundIndexOffset,stop - Sound._SoundIndexOffset)
# pass #TODO
#
# def getSamplingRate(sound):
# #if not isinstance(sound, Sound):
# # #print "getSamplingRate(sound): Input is not a sound"
# # #raise ValueError
# # repValError("getSamplingRate(sound): Input is not a sound")
# #return sound.getSamplingRate()
# pass #TODO
#
# def setSampleValueAt(sound,index,value):
# #if not isinstance(sound, Sound):
# # print "setSampleValueAt(sound,index,value): First input is not a sound"
# # raise ValueError
# #if index < Sound._SoundIndexOffset:
# # print "You asked for the sample at index: " + str( index ) + ". This number is less than " + str(Sound._SoundIndexOffset) + ". Please try" + " again using an index in the range [" + str(Sound._SoundIndexOffset) + "," + str ( getLength( sound ) - 1 + Sound._SoundIndexOffset ) + "]."
# # raise ValueError
# #if index > getLength(sound) - 1 + Sound._SoundIndexOffset:
# # print "You are trying to access the sample at index: " + str( index ) + ", but the last valid index is at " + str( getLength( sound ) - 1 + Sound._SoundIndexOffset )
# # raise ValueError
# #sound.setSampleValue(index-Sound._SoundIndexOffset,int(value))
# pass #TODO
#
# def getSampleValueAt(sound,index):
# #if not isinstance(sound,Sound):
# # print "getSampleValueAt(sound,index): First input is not a sound"
# # raise ValueError
# #if index < Sound._SoundIndexOffset:
# # print "You asked for the sample at index: " + str( index ) + ". This number is less than " + str(Sound._SoundIndexOffset) + ". Please try" + " again using an index in the range [" + str(Sound._SoundIndexOffset) + "," + str ( getLength( sound ) - 1 + Sound._SoundIndexOffset ) + "]."
# # raise ValueError
# #if index > getLength(sound) - 1 + Sound._SoundIndexOffset:
# # print "You are trying to access the sample at index: " + str( index ) + ", but the last valid index is at " + str( getLength( sound ) - 1 + Sound._SoundIndexOffset )
# # raise ValueError
# #return sound.getSampleValue(index-Sound._SoundIndexOffset)
# pass #TODO
#
# def getSampleObjectAt(sound,index):
# #if not isinstance(sound, Sound):
# # print "getSampleObjectAt(sound,index): First input is not a sound"
# # raise ValueError
# # return sound.getSampleObjectAt(index-Sound._SoundIndexOffset)
# #if index < Sound._SoundIndexOffset:
# # print "You asked for the sample at index: " + str( index ) + ". This number is less than " + str(Sound._SoundIndexOffset) + ". Please try" + " again using an index in the range [" + str(Sound._SoundIndexOffset) + "," + str ( getLength( sound ) - 1 + Sound._SoundIndexOffset ) + "]."
# # raise ValueError
# #if index > getLength(sound) - 1 + Sound._SoundIndexOffset:
# # print "You are trying to access the sample at index: " + str( index ) + ", but the last valid index is at " + str( getLength( sound ) - 1 + Sound._SoundIndexOffset )
# # raise ValueError
# #return Sample(sound, index-Sound._SoundIndexOffset)
# pass #TODO
#
# def setSample(sample,value):
# #if not isinstance(sample,Sample):
# # print "setSample(sample,value): First input is not a sample"
# # raise ValueError
# #if value > 32767:
# # value = 32767
# #elif value < -32768:
# # value = -32768
# ## Need to coerce value to integer
# #return sample.setValue( int(value) )
# pass #TODO
#
# # PamC: Added this function to be a better name than setSample
# #Done
# def setSampleValue(sample, value):
# setSample(sample, value)
#
# def getSample(sample):
# #if not isinstance(sample, Sample):
# # print "getSample(sample): Input is not a sample"
# # raise ValueError
# #return sample.getValue()
# pass #TODO
#
# # PamC: Added this to be a better name for getSample
# #Done
# def getSampleValue(sample):
# return getSample(sample)
#
# def getSound(sample):
# #if not isinstance(sample,Sample):
# # print "getSound(sample): Input is not a sample"
# # raise ValueError
# #return sample.getSound()
# pass #TODO
#
# def getLength(sound):
# #if not isinstance(sound, Sound):
# # print "getLength(sound): Input is not a sound"
# # raise ValueError
# #return sound.getLength()
# pass #TODO
#
# # PamC: Added this function as a more meaningful name for getLength
# #Done
# def getNumSamples(sound):
# return getLength(sound)
#
# # PamC: Added this function to return the number of seconds
# # in a sound
# def getDuration(sound):
# #if not isinstance(sound, Sound):
# # print "getDuration(sound): Input is not a sound"
# # raise ValueError
# #return sound.getLength()/sound.getSamplingRate()
# pass #TODO
#
# def writeSoundTo(sound,filename):
# #global mediaFolder
# #if not os.path.isabs(filename):
# # filename = mediaFolder + filename
# #if not isinstance(sound, Sound):
# # print "writeSoundTo(sound,filename): First input is not a sound"
# # raise ValueError
# #sound.writeToFile(filename)
# pass #TODO
#
# ##
# # Globals for styled text
# ##
# def makeStyle(fontName,emph,size):
# #return awt.Font(fontName,emph,size)
# pass #TODO
#
# sansSerif = "SansSerif"
# serif = "Serif"
# mono = "Monospaced"
# #italic = awt.Font.ITALIC TODO
# #bold = awt.Font.BOLD TODO
# #plain = awt.Font.PLAIN TODO
##
## Global color functions
##
# Buck Scharfnorth (28 May 2008): if bool == 1 colors will be (value % 256)
# if bool == 0 colors will be truncated to 0 or 255
# updated (13 May 2009):
# THIS GLOBAL FUNCTION CHANGES JES SETTINGS - this value overwrites
# the value in the JES options menu.
def setColorWrapAround(bool):
#JESConfig.getInstance().setSessionWrapAround( bool )
pass #TODO
# Buck Scharfnorth (28 May 2008): Gets the current ColorWrapAround Value
def getColorWrapAround():
#return JESConfig.getInstance().getSessionWrapAround()
pass #TODO
# Buck Scharfnorth (28 May 2008): Modified to no longer assume the value is 0-255
#Done
def _checkPixel(raw):
value = int(raw)
if getColorWrapAround():
value = (value % 256)
else:
if value < 0:
value = 0
if value > 255:
value = 255
return value
# this class is solely for the purpose of
# making makeLighter makeDarker work.
# both of these functions destructively modify a color
# and a color in java is a constant value so we have to put
# this python interface here
#
# Buck Scharfnorth (28 May 2008): Modified to no longer assume the value is 0-255
# and the gray Color constructor to allow only 1 color parameter (will take 2, but ignores the second)
class Color:
def __init__(self,r,g=None,b=None):
if b == None:
#In this case, r should be a tuple or Color or QColor
if isinstance(r, Color):
self.r = r.getRed()
self.g = r.getGreen()
self.b = r.getBlue()
elif isinstance(r, QColor):
self.r = r.red()
self.g = r.green()
self.b = r.blue()
elif isinstance(r, int):
#This case is necessary because of how QImage.pixel() works
cl = QColor(r)
self.r = cl.red()
self.g = cl.green()
self.b = cl.blue()
else:
self.r = r[0]
self.g = r[1]
self.b = r[2]
#if isinstance( r, awt.Color ) or isinstance( r, Color ):
# self.color = r
#else:
# val = _checkPixel(r)
# self.color = awt.Color( val, val, val )
else:
# self.color = awt.Color(r,g,b)
#self.color = awt.Color( _checkPixel(r), _checkPixel(g), _checkPixel(b) )
if not isinstance(r, numbers.Number):
repValError("First color component (red) not a number")
#raise ValueError
if not isinstance(g, numbers.Number):
repValError("Second color component (green) not a number")
#raise ValueError
if not isinstance(b, numbers.Number):
repValError("Third color component (blue) not a number")
#raise ValueError
self.r = r
self.g = g
self.b = b
#Fix out-of-bounds
self.validateColor()
#If any component is not in range 0 to 255, fix that
#If any component is not an integer, fix that
def validateColor(self):
if self.r < 0:
self.r = 0
elif self.r > 255:
self.r = 255
if self.g < 0:
self.g = 0
elif self.g > 255:
self.g = 255
if self.b < 0:
self.b = 0
elif self.b > 255:
self.b = 255
if not isinstance(self.r, int):
self.r = int(self.r)
if not isinstance(self.g, int):
self.g = int(self.g)
if not isinstance(self.b, int):
self.b = int(self.b)
def __str__(self):
return "color r="+str(self.getRed())+" g="+str(self.getGreen())+" b="+str(self.getBlue())
def __repr__(self):
return "Color("+str(self.getRed())+", "+str(self.getGreen())+", "+str(self.getBlue())+")"
def __eq__(self,newcolor):
return ((self.getRed() == newcolor.getRed()) and (self.getGreen() == newcolor.getGreen()) and (self.getBlue() == newcolor.getBlue()))
def __ne__(self,newcolor):
return (not self.__eq__(newcolor))
#def __tojava__(self, javaclass):
# if javaclass == awt.Color:
# return self.color
# else:
# return self
#Added by BrianO
def __add__(self, other):
r = self.getRed() + other.getRed()
g = self.getGreen() + other.getGreen()
b = self.getBlue() + other.getBlue()
# if(wrapAroundPixelValues):
# r = r % 256
# g = g % 256
# b = b % 256
# return Color(r,g,b)
#return Color( _checkPixel(r), _checkPixel(g), _checkPixel(b) )
return Color(r, g, b)
#Added by BrianO
def __sub__(self, other):
r = self.getRed() - other.getRed()
g = self.getGreen() - other.getGreen()
b = self.getBlue() - other.getBlue()
# if(wrapAroundPixelValues):
# r = r % 256
# g = g % 256
# b = b % 256
# return Color(r,g,b)
#return Color( _checkPixel(r), _checkPixel(g), _checkPixel(b) )
return Color(r, g, b)
def setRGB(self, r, g, b):
# # self.color = awt.Color(r,g,b)
# self.color = awt.Color(_checkPixel(r), _checkPixel(g), _checkPixel(b))
if not isinstance(r, numbers.Number):
repValError("First color component (red) not a number")
#raise ValueError
if not isinstance(g, numbers.Number):
repValError("Second color component (green) not a number")
#raise ValueError
if not isinstance(b, numbers.Number):
repValError("Third color component (blue) not a number")
#raise ValueError
self.r = r
self.g = g
self.b = b
self.validateColor()
def getRed(self):
#return self.color.getRed()
return self.r
def getGreen(self):
#return self.color.getGreen()
return self.g
def getBlue(self):
#return self.color.getBlue()
return self.b
def distance(self, othercolor):
r = pow((self.getRed() - othercolor.getRed()),2)
g = pow((self.getGreen() - othercolor.getGreen()),2)
b = pow((self.getBlue() - othercolor.getBlue()) ,2)
return math.sqrt(r+g+b)
def makeDarker(self):
#return self.color.darker()
return Color(min(int(self.getRed() * 0.7), 0), min(int(self.getGreen() * 0.7), 0), min(int(self.getBlue() * 0.7), 0))
def makeLighter(self):
#return self.color.brighter()
return Color(max(int(self.getRed() / 0.7), 255), max(int(self.getGreen() / 0.7), 255), max(int(self.getBlue() / 0.7), 255))
def getRGB(self):
return (self.getRed(), self.getGreen(), self.getBlue())
#Convert to QColor
def toQColor(self):
return QColor(*self.getRGB())
#Convert to color integer
def toQColorInt(self):
return self.toQColor().rgb()
#Done
def pickAColor():
## Dorn 5/8/2009: Edited to be thread safe since this code is executed from an
## interpreter JESThread and will result in an update to the main JES GUI due to
## it being a modal dialog.
#from java.lang import Runnable
#class pickAColorRunner(Runnable):
#color = Color(0,0,0)
#def run(self):
# retValue = swing.JColorChooser().showDialog(swing.JFrame(),"Choose a color", awt.Color(0,0,0))
# if retValue != None:
# self.color = Color(retValue.getRed(),retValue.getGreen(),retValue.getBlue())
#runner = pickAColorRunner()
#swing.SwingUtilities.invokeAndWait(runner)
#return runner.color
#root.lift()
#root.update()
# root = tkinter.Tk()
# root.withdraw()
# #root.lift()
#
# if platform() == 'Darwin': # How Mac OS X is identified by Python
# system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''')
#
# root.focus_force()
# col = askcolor()
# root.update()
# root.destroy()
col = QColorDialog.getColor()
#return Color(int(col[0][0]), int(col[0][1]), int(col[0][2]))
return Color(col)
def colorPalette():
'''The built-in colors that you can use are:
black
white
blue
red
green
gray
darkGray
lightGray
yellow
orange
pink
magenta
cyan
'''
print ('''The built-in colors that you can use are:
black
white
blue
red
green
gray
darkGray
lightGray
yellow
orange
pink
magenta
cyan
''')
#Constants
black = Color(0,0,0)
white = Color(255,255,255)
blue = Color(0,0,255)
red = Color(255,0,0)
green = Color(0,255,0)
gray = Color(128,128,128)
darkGray = Color(64,64,64)
lightGray = Color(192,192,192)
yellow = Color(255,255,0)
orange = Color(255,200,0)
pink = Color(255,175,175)
magenta = Color(255,0,255)
cyan = Color(0,255,255)
#Pixel class, because JES has one
class Pixel:
#Constructor
def __init__(self, picture, x, y):
self.picture = picture
self.x = x
self.y = y
#self.color = Color(picture.getpixel((x,y)))
self.color = picture.getPixelColor(x, y)
#Render as string
def __str__(self):
return "Pixel red=%d green=%d blue=%d" % self.color.getRGB()
#Get red
def getRed(self):
return self.color.getRed()
#Get green
def getGreen(self):
return self.color.getGreen()
#Get blue
def getBlue(self):
return self.color.getBlue()
#Get color
def getColor(self):
return self.color
#Set color
def setColor(self, r, g=None, b=None):
if g == None:
if isinstance(r, Color):
self.color = r
elif isinstance(r, tuple) and len(r) == 3:
self.color = Color(r)
else:
repValError("Invalid color arguments")
#raise ValueError
else:
self.color = Color(r, g, b)
self.updatePicture()
#Set red
def setRed(self, r):
self.color = Color(r, self.color.getGreen(), self.color.getBlue())
self.updatePicture()
#Set green
def setGreen(self, g):
self.color = Color(self.color.getRed(), g, self.color.getBlue())
self.updatePicture()
#Set blue
def setBlue(self, b):
self.color = Color(self.color.getRed(), self.color.getGreen(), b)
self.updatePicture()
#Get color
def getColor(self):
return self.color
#Get x
def getX(self):
return self.x
#Get y
def getY(self):
return self.y
#Update picture
def updatePicture(self):
self.picture.setPixel(self.x, self.y, self.color)
#Picture class
#Mostly just a wrapper for QImages
class Picture:
#Constructor
def __init__(self, width = None, height = None, aColor = None):
global keepAround
if isinstance(width, Picture):
#We're duplicating a picture
self.height = width.image.height()
self.width = width.image.width()
self.filename = width.filename
self.image = QImage(width.image)
else:
#We're making a blank picture
self.filename = None
self.height = height
self.width = width
if height != None:
if isinstance(aColor, Color):
col = aColor.getRGB()
elif isinstance(aColor, QColor):
col = (aColor.red(), aColor.green(), aColor.blue())
else:
col = aColor
#Qt image
self.image = QImage(width, height, QImage.Format_RGB32)
if col is not None:
self.image.fill(QColor(*col))
#Set up a window for displaying it
self.window = QWidget()
if self.filename == None:
self.window.setWindowTitle("Image")
else:
self.window.setWindowTitle(self.filename)
self.picLabel = QLabel(self.window)
#self.frame = None
if self.height != None:
self.window.resize(self.width, self.height)
#Keep a copy around forever (bad to do generally, but important for this)
keepAround.append(self)
#Match JES's printing of a picture
def __str__(self):
ret = "Picture, "
if self.filename == None and self.height == None:
return ret + "empty"
retend = "height %d width %d" % (self.height, self.width)
if self.filename == None:
return ret + retend
else:
return ret + "filename %s %s" % (self.filename, retend)
#Load a file into the Picture object
def loadOrFail(self, filename):
try:
#Check if it's supported
suppt = isSupportedImageFormat(filename)
if not suppt:
#print("Warning! Attempting to open unsupported file type!")
##Make a PNG and mess with that instead
#First, open a PIL image
self.pil_im = PIL.Image.open(filename)
#Next, create a temporary PNG file
tmpfl = tempfile.mkstemp(suffix = '.png')
#Now, keep track of the file name to work with
self.workfile = tmpfl[1]
#Finally, export the PIL image as a PNG to the temp file
self.pil_im.save(tmpfl[1])
else:
#Nothing went wrong, so pil_im should be None
self.pil_im = None
#The "actual" file is the same as the specified file
self.workfile = filename
#self.image = PIL.Image.open(filename)
#Load the QImage
self.image = QImage(self.workfile)
if self.image.isNull():
#Load failed
#raise IOError
reportErrorToUser(IOError, "Loading image failed")
self.filename = filename
self.height = self.image.height()
self.width = self.image.width()
self.window.resize(self.width, self.height)
self.window.setWindowTitle(self.filename)
except IOError:
raise IOError(filename + " could not be opened or was not a picture. Check that you specified the path")
#Set all pixels to a color
def setAllPixelsToAColor(self, col):
self.image.fill(QColor(*col.getRGB()))
#Get Pixels
def getPixels(self):
##Get the raw data
#dat = self.image.getdata()
##Convert them all to Pixel objects
#return [Pixel(self,
#On second thought, let's just mirror the Pixel class in JES
return [Pixel(self, x, y) for y in range(self.height) for x in range(self.width)]
#Get Pixel
def getPixel(self, x, y):
return Pixel(self, x, y)
#Get pixel color
def getPixelColor(self, x, y):
return Color(self.image.pixel(x, y))
#Get width
def getWidth(self):
return self.width
#Get height
def getHeight(self):
return self.height
#Set the (x,y) pixel to Color col
def setPixel(self, x, y, col):
if not isinstance(col, Color):
repValError("non-color passed to setPixel")
#raise ValueError
#self.image.putpixel((x,y), col.getRGB())
#NOTE: There's a warning about this being a slow operation
self.image.setPixel(x, y, col.toQColorInt())
#Print the picture in Canopy
#TODO make Windows-friendly
def printPicture(self):
#return self.image
#Canopy prints out PIL images nicely
#So, we'll convert to and return a PIL image
#This is very hack-ish
#img = QImage("/tmp/example.png")
img = QImage(self.image)
#Create a temporary file
tmpfl = tempfile.mkstemp(suffix = '.png')
#print(tmpfl)
#tmpfl.close()
#img.save("/tmp/example.png", "PNG")
#pil_im = PIL.Image.open("/tmp/example.png")
img.save(tmpfl[1], "PNG")
pil_im = PIL.Image.open(tmpfl[1])
# buffer = QBuffer()
# buffer.open(QIODevice.ReadWrite)
# img.save(buffer, "PNG")
#
# strio = io.BytesIO()
# strio.write(buffer.data())
# buffer.close()